Javascript has two equality operators, == and === (and corresponding inequality operators != and !==). Most beginner javascript developers use either ==, as they don’t yet know about ===, or blindly use === for every comparison because they heard once, somewhere, that that was what you should do in javascript;¬†without really understanding the differences between the two.

The difference between == and === are simple: == uses ‘type coercion’, which means that it can attempt to match two objects of different class, while === compares against both value and type. For example,

"1" == 1 // true

but

"1" === 1 // false

since javascript’s == comparison converts the string “1″ to a number, and then matches, whilst the === recognises that the string literal is not equivalent to the number. The results of == seem ok for this example, but it’s type conversions can produce some other unexpected results. for example:

"0" == false // true
"0" === false // false

1 == true // true
1 === true // false

undefined == null // true
undefined === null // false

On the whole it is advisable to use === for comparisons, but knowing the difference means that sometimes we can use this type coercion to our advantage. Just be sure to be smart about it, and preferably explain your reasoning in a short comment so as not to confuse others!

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>