5

W3 Schools says

These two different statements both create a new array containing 6 numbers:

 var points = new Array(40, 100, 1, 5, 25, 10)  // Bad 
 var points =[40, 100, 1, 5, 25, 10];          // Good

but doesn't give an explanation why the first is bad.

From what I understand, the only difference is that the first calls the constructor. Can someone clue me into why the first is bad?

djechlin
  • 59,258
  • 35
  • 162
  • 290
Steve Jobs
  • 181
  • 5
  • 1
    Where did you read it's bad? – mellis481 Mar 25 '15 at 15:43
  • 2
    W3 schools has a lot of bad and downright wrong information. You should literally never go there. – djechlin Mar 25 '15 at 15:43
  • W3Schools is indeed a bad resource, but it's right in this case. – Ingo Bürk Mar 25 '15 at 15:44
  • 2
    W3S might be wrong in some places but it's success tells me something: Other projects should make their documentation more consistent and improve their usability. I'm well aware of its quirks but sometimes I just use the site because I immediately find what I'm looking for while other documentation pages are a pain to read compared to them. – floriank Mar 25 '15 at 15:52
  • 2
    other sites "are a pain to read" ... ??? Mozilla Developer Network (MDN) gives definitions that are clear, often with examples and secondary links for more informations. The time lost by having a wrong information (W3S has so much of them) make this commercial site just wrong. On the other side, googling "MDN the_thing_i_seek" provides perfect information as first link 99% of the time. – GameAlchemist Mar 25 '15 at 16:11

1 Answers1

17

The true reason is that this constructor is inconsistent.

var points = new Array(40)

creates an array of size 40 and no content while

var points = new Array(40, 50)

creates an array of size 2 with 2 elements.

It's just simpler and more readable to use

var points = [40];

or

var points = [40, 50];

There's also no reason to use this constructor when you want to build a array, just use a literal array, exactly like you're using literal numbers.

Only use the Array constructor when you want to build an empty array with a given size (which should be very rare).

ES 2015 edit:

Due to this inconsistency, ES2015 brought us a new static function, Array.of. Array.of(40) makes the [40] array.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • You could mention that the array length can also be set after instantiating an empty array. For example `var a = []; a.length = 50;`. – soyuka Mar 25 '15 at 16:03
  • Well... yes, but why would you write that ? I'd rather user `new Array(50)` in this specific case. – Denys Séguret Mar 25 '15 at 16:09
  • The first example I can think of, would be to make a `copy` of an existing array for a comparison. [Use case here](https://gist.github.com/soyuka/950371df21c0947535f3#file-concurrency-js-L11). It's also a way to have the same behavior as `new Array(length)`. – soyuka Mar 25 '15 at 16:12