X

Learn to love the === operator in JavaScript

Javascript

In JavaScript there are two types of equality operator, the === and the !== , sorry I forgot to mention their evil twin == and != .

tsdr; (too short didn’t read) Use three equals unless you fully understand the conversions that take place for two-equals.

Basically what the triple equal (===) compares is if the value is equal and if the type is equal.

Lets look at an example below.

true == 1; //true, because 'true' is converted to 1
"1" == 1; //again true

true === 1 //false
"2" === 2 //false

The reason for the === operator to return false is due to the fact that it does not do type coercion, but the double == does type coercion and implicitly tries to convert the value before comparing.

Some additional examples:

var x = [1,2,3];
var y = [1,2,3];
var z = x;

alert(x === y); // false (even though x and y are the same type)
alert(x === z); // true

var str1 = "ab" + "c";
var str2 = "abc";

alert(str1 === str2); // returns true, because strings behave like value types

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

I hope the examples above give you the reason to stop using == and != since it convert things for you during comparison. So start using the triple === and !== .

Below are two tables that show the equality of == and === provide by http://dorey.github.io/JavaScript-Equality-Table/

x == y

x === y

Taswar Bhatti:

View Comments (1)

  • Great explanation of JavaScript operators, especially the comparison between === and ==. The examples make it easy to understand how strict equality works and why it’s recommended in real projects. Really helpful for beginners who want to avoid common JS mistakes.

Related Post