3

Here is the examples

Array(1,2,3)
> [1,2,3]
new Array(1,2,3)
> [1,2,3]
Array(3)
> [undefined, undefined, undefined]
new Array(3)
> [undefined, undefined, undefined]

I saw some comments about "never use Array with new". But I can't understand as I found Array and new Array seems to behave the same in Javascript.. Why do they behave the same? And why should one usage be preferred over the other?

I know [] literal syntax should usually be used instead of Array, I was just wondering what Array is..

Is it a constructor function? If it is a constructor function, why could it be used without new?

8
  • 1
    Actually neither new Array() nor Array() should be used. Use the literal syntax instead, i.e. [1, 2, 3]. Btw there is nothing in JavaScript from stopping you to call a constructor function without new. Commented Jun 1, 2015 at 12:07
  • care to share the comments you are mentioning so we know the context? :) I actually prefer the simple [] version :) Commented Jun 1, 2015 at 12:07
  • 2
    Don't use either Array(1,2,3) or new Array(1,2,3). Always use [1,2,3]. Commented Jun 1, 2015 at 12:09
  • @helpermethod I know [] is usually the best choice.. Just wondering what Array actually is.. Commented Jun 1, 2015 at 12:11
  • 1
    @Salketer Because new Array() behaves in unexpected ways. E.g. new Array(8) initializes an 8 element array, whereas new Array(8, 9) initializes an array with the elements 8 and 9. [8] on the other hand gives you an array containing the element 1. Also [] is shorter. Commented Jun 1, 2015 at 12:32

1 Answer 1

8

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

http://es5.github.io/#x15.4.1

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! looked all over documentation, but you found it! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.