javascript interactive

JavaScript Interactive — a console crash course


4.6 Native Value Objects

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
new Number(1)
1
As mentioned in 1.2. Object Types, JavaScript contains a number of built-in object types (or constructor functions, really).
>>>
new Number(1) == 1
true
It is common to make assumptions about these objects...
>>>
new Number(1) == new Number(1)
false
...and be wrong. In reality, the Number objects are wrappers around a primitive number value. They are not one and the same.
>>>
new Number(1).valueOf()
1
The built-in valueOf() method helps to explain what just happened. It is called to coerce an object to a primitive value type (i.e. boolean, number or string).
>>>
new Number(1) === 1
false
When avoiding type coercion, the first comparison from above now shows that the values are indeed different. The second result from above is explained by normal object comparison.
>>>
(1).constructor
function Number() {
    [native code]
}
But lets not pretend that logic always prevail. Any primitive boolean, number or string value will happily masquerade as an instance of the corresponding wrapper object.
>>>

Index 1 2 3 4 5 6 7 8