Professional Documents
Culture Documents
Doublevstriplequals
Doublevstriplequals
Triple Equals
When using triple equals === in JavaScript, we are testing for
strict equality. This means both the type and the value we
are comparing have to be the same.
Lets look at a couple examples of strict equality.
In this first example we’re comparing the number 5 with the
number 5. As expected, true is returned. Both are numbers,
and both share the same value of 5.
5 === 5
// true
77 === '77'
Double equals
When using double equals in JavaScript we are testing for
loose equality. Double equals also performs type
coercion.
after attempting to convert them into a common type.
An example will illustrate this. Recall earlier when we tested
the following with strict equality:
77 === '77'
77 == '77'
// true
equals 0:
false === 0
false == 0
// true
Falsy Values
Okay, so why does false == 0 in JavaScript? It’s complex, but
it’s because in JavaScript 0 is a falsy value.
Type coercion will actually convert our zero into a false
boolean, then false is equal to false.
•undefined
•NaN — Not A Number
Falsy Value Comparison
The following you can consider to be ‘rules’ of falsy values.
These are things you should ultimately memorize if you will
be working with JavaScript often.
1.false, 0, and ""
When comparing any of our first three falsy values with
loose equality, they will always be equal! That’s because
these values will all coerce into a false boolean.
false == 0
// true0 == ""
// true"" == false
// true
null == null
// trueundefined == undefined
// truenull == undefined
// true
3. NaN
Lastly, NaN is not equivalent to anything. Even cooler, it’s not
even itself!
NaN == null
// falseNaN == undefined
// falseNaN == NaN
// false
Key Takeaways
•As you’ve seen, type coercion can get a bit crazy in JS.
Unless you’re very familiar with JavaScript, loose equality
can lead to more headaches than it’s worth. Memorizing
the six falsy values and the rules associated with them
can go a long way towards understanding loose equality.
•Triple Equals is superior to double equals.
Whenever possible, you should use triple equals to
test equality. By testing the type and value you
can be sure that you are always executing a true
equality test.