Last Updated: February 25, 2016
· jjperezaguinaga
Me 180x180

Why always use '===' in Javascript

One example is better than a thousand words.

new Number(10) == 10 // true
new Number(10) === 10 // false

What's going on? You are comparing an object to a primitive value. This is because of the use of they keyword new

typeof Number(10) // returns number
typeof 10 // returns number
typeof new Number(10) // returns object

This is a common error for people that think that everything in Javascript is an object* an use the new word carelessly.

  • (Wait, it's not? Then why can I do (10).toString()? Javascript "wraps" primitive values into "complex objects" when you use methods with them, but then unwraps them after you finish, returning them to their non-object values)
Say Thanks

2 Responses
Add your response


If you know you're comparing same types == is just fine.
Am i right?

over 1 year ago ·
Profile pic2

Mostly yes, but are you always sure about those types? Look at the first example, is it logical that new Number(10) !== 10 ? IMO not rly. That's why use of === is another best practice in JS.

over 1 year ago ·