Home  > Resources  > Blog

JavaScript Equality Operators

 
August 25, 2011 by Bibhas Bhattacharya
Category: Ajax & Web 2.0

We use equality operators like == and != all the time. They appear to be same as Java or C++ on the surface. But, in reality, things are a lot more complicated and confusing. I will try to explain a few things that may not be obvious.

The Equals Operator (==)

var result = (expr1 == expr2);

When expr1 and expr2 are numbers, a simple number comparison is done. If either of the numbers is a NaN then false is returned.

When expr1 and expr2 are string values, then a string equality is done. If both strings are of equal length and have the same sequence of characters then true is returned.

If one expression is a string and the other a number, then the string is converted to a number before comparison.

var s1 = "10";
var s2 = 10;

var result = (s1 == s2); //result is true

When an object is compared with a number or string, then the system converts the object into number or string prior to comparison.

var s1 = 10;
var s2 = new String("10");

var result = (s1 ==s2);  //result is true

This is same as:

var result = (s1 == Number(s2)); //result is true

When expr1 and expr2 are objects then true is returned if both expressions point to the same exact object. This is where things can get interesting. Consider this example:

var s1 = new String("abc123");
var s2 = new String("abc123");

var result = (s1 == s2); //result is false

Here, result will be false. Variables s1 and s2 are of type object and not string. Since they point to two separate object instances, the equality test fails.

Boolean expressions are converted to number before comparison. There, true converts to 1 and false converts to 0.

var result = (true == 1); //result is true

The null and undefined values are different things in JavaScript. But, they are treated as equals by the operator.

var s1 = null;
var s2; //undefined

var result = (s1 == s2);  //result is true

The Does-not-equals Operator ( != )

This is a reverse of the equals operator. Nothing new to discuss.

The Strict Equals Operator ( === )

This operator tests for type equality in addition to value. If expressions are of different types, then false is returned. It does not do any type conversion like the regular equals operator.

var s1 = "10";
var s2 = 10;

var result = (s1 === s2);  //result is false
result = (s1 == s2); //result is true

Hence, to see if a variable is truly undefined, use the strict test:

var s1 = null;

alert(s1 == undefined); //Wrong! Shows true
alert(s1 === undefined); //Correct. Shows false

The Strict Does-not-equal Operator ( !== )

This is a reverse of the strict equals operator.

Follow Us

Blog Categories