Professional Development

JavaScript “==” Versus “===”

When first learning JavaScript one of the weird things you run across are the comparison operators “==” and “===”. One equal sign “=” is used to assign a value, such as:

var myVariable = “Hello World”;

Thus the comparison operators, to differentiate, are “==” and “===”. But what is the difference between “==” and “===”? At first they can seem to be a bit of a mystery, and their behavior strange. See, for example (and you can test these in the console to see for yourself):

4 == “4” // true. This is part of “weak” variable typing in JavaScript
undefined == null // true. This is a bit strange…
undefined === null // false. The operators perform differently in this case?
undefined === undefined // true. good 🙂
4 === 4 // true. Expected.
{} === {} // false. umm?
NaN === NaN // false. Huh?!
true == {valueOf: function(){return “1”}} // true !!

To fundamentally understand the behavior one must understand the decision tree each operator performs. This is what the decision tree looks like for “===”:

===

This says if the types does not match, already we have false. That’s why:

undefined === null // false
4 === “4” // false
true === 1 // false

Moving to the second decision, if the types do match, the comparison is done bitwise for primitives (numbers, strings, Booleans, undefined, and nulls) and by address otherwise (i.e. for objects). That is why:

4 === 6 // false
null === null // true

but:

{} === {} // false

because although you’re looking a two empty objects, they take up difference space (addresses) in memory.

The decision tree for “==” is markedly more complicated:

==

What’s happening here is:

  1. Check if the type is the same, if so see the “===” process flow
  2. If both x and y are null or undefined, they’re equal
  3. If x is a string, and y is a number, convert x to the a number or NaN (e.g. if x = “6” then x = 6, if x = “abc” then x = NaN), and return to step 1. This is why 6 == “6” returns true.
  4.  If x is a boolean, convert x to 1. This is, with decision 5, why true == {valueOf: function(){return “1”}} returns true
  5. If x is an object and y is a string or number, stringify x and go back to step 1.

As you can see, the “==” decision tree is more complex than the “===” decision tree, and in many cases involves more than one iteration to get a value (true or false). This is why “===” is the preferred comparison operator.

 

 

 

Advertisements

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 )

Google+ photo

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

Connecting to %s