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)
Written by Jose Jesus Perez Aguinaga
Related protips
2 Responses
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
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#