Posted by: robrobertson | January 18, 2012

JavaScript === (Triple Equals)

Coming across a “===” in some JavaScript today and wondered what the difference was between the normal equality operater (==) and this super version. JavaScript: The Definitive Guide differiantes the two as being Equality vs Identity. The ECMAScript Spec merely labels it as the “Strict Equals Operator”.

An interesting example is (“1″ == true )

Since the string “1″ evaluates to the integer 1 and the boolean true evaluates to the integer 1, the values are treated as equals.

(“1″ === true) is immediately evaluated to false since the string and boolean are different types.

Just in case you’re curious, here’s the comparison algorithm from the ECMA Spec, Section 11.9.6:

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

1. If Type(x) is different from Type(y), return false.
2. If Type(x) is Undefined, return true.
3. If Type(x) is Null, return true.
4. If Type(x) is Number, then
a. If x is NaN, return false.
b. If y is NaN, return false.
c. If x is the same Number value as y, return true.
d. If x is +0 and y is ?0, return true.
e. If x is ?0 and y is +0, return true.
f. Return false.
5. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and
same characters in corresponding positions); otherwise, return false.
6. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
7. Return true if x and y refer to the same object. Otherwise, return false.

It definitely seems like a safer bet to control the conversion of your datatypes.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.