Last Updated: May 23, 2019
·
4.117K
· jjperezaguinaga

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)

2 Responses
Add your response

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

over 1 year ago ·

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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside