JavaScript Equality Operators

SCC00WCQ3I Boolean values are converted to numbers before comparisons are made with the equal operator (==) and not equal operator (!=).

Comparisons where one operand is a string and the other is a number converts the string to a number first.

If one of the operands is an object and not the other then the object is evaluated with the valueOf() function first.

null and undefined are equal and can’t be converted to other values.

NaN is considered false.

Here are a couple of other interesting facts about equality in JavaScript:

var x = (NaN == NaN);  //false because NaN is not equal to NaN by rule
var x = (true == 2);   //false because true is converted to 1 first

if both operands are objects, the equal operator returns true if they both point to the same object.

Identically equal (===) and identically not equal (!--) don’t convert values before the comparison. Values that are not the same type will not be equal.

var x = ("2" == 2); //true "2" is converted to 2
var x = ("2" === 2); //false "2" is not converted and a string is not equal to a number
var x = (null == undefined); //true
var x = (null === undefined); //false

JavaScript allows for compound assignment operators (+=, *=, /=, %= and -=);

var x = 10;
x += 10;     // 20, same as x = x + 10;

The comma allows more than one assignment in a single statement.

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top