DEV Community

Discussion on: What you need to know about Javascript's Implicit Coercion

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

The last thing I recall biting me in JS and I didn't see it mentioned above:

3 === new Number(3)  // false
3 === Number(3)      // true
Enter fullscreen mode Exit fullscreen mode

The first one is false because new creates a Number object instance which is compared by reference. Value does not equal object reference.

typeof new Number(3) // object
Enter fullscreen mode Exit fullscreen mode

The second one is true because it is a function which returns a value type.

typeof Number(3)     // number
typeof 3             // number
Enter fullscreen mode Exit fullscreen mode

This is a Javascript feature that is best avoided.

Type coercion is one of the worst parts of JS. I could not even count the number of hours I have wasted tracking down bugs because of this "feature". It is one of the main reasons I avoid the language.

Collapse
 
promisetochi profile image
Promise Tochi

Yeah, object wrappers. They almost never have an advantage over the normal primitives.

Those sort of bugs can truly be frustrating.