Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `new Array(new Number(3))` produce an array of length 3?

Tags:

javascript

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?

  1. Can someone link me to a standards doc where this Array behaviour is specified?
  2. Is this something that I need to watch out for in general, or is it specific to the Array constructor?

Thanks!


2 Answers

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

  1. Let defineStatus be CreateDataProperty(array, "0", len).
  2. Assert: defineStatus is true.
  3. Let intLen be 1.
like image 60
ak13 Avatar answered Jan 20 '26 16:01

ak13


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
like image 21
Fabio Avatar answered Jan 20 '26 16:01

Fabio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!