When I write new Array(new Number(3)) in the console, it produces an array of length 1 with that item being a Number object with valueOf=3. Why does the array constructor treat new Number(3) different to the primitive version of 3?
Array behaviour is specified?Thanks!
Because in new Array(new Number(3)), the parameter new Number(3) returns an object and not the number.
Where as new Array(Number(3)) will work as Number(3) returns 3, the number.
Thanks to @Andreas' comment, here's the specification: ECMAScript 22.1.1.2 Array (len)
Step 7: "If Type(len) is not Number, then
- Let defineStatus be CreateDataProperty(array, "0", len).
- Assert: defineStatus is true.
- Let intLen be 1.
From the MDN
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number
Instance of new Number(3) is not an integer(number).
Number.isInteger(3) // -> true
Number.isInteger(Number(3)) // -> true
Number.isInteger(new Number(3)) // -> false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With