Is there any difference between these three ways of creating an array?

javascript, jquery

Solution

Using `[]` is more secure and reliable than using `new Array()`. The former is actually recommended. This is because the value of `Array` can be overridden. Also, `[]` is faster compared to `new Array()`.

Take a look at these related questions:

- What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

- JSLint: “Use the array literal notation []” for var os_map = {}

- What's wrong with var x = new Array();

- Is JavaScript 's “new” Keyword Considered Harmful?

A related link:

- JSLint wants you to avoid `new`.

To clarify what "overridden" means, you can do something like this:

function Array() {
    alert("I am not really an array! BWAHAHAHAHAHA!");
}

Now when you do `new Array();` you will get an alert, which is obviously not what you want.

In short, there really is no pressing need to to use `new Array()` and it doesn't buy you anything more compared to using the literal `[]`.

Problem

Is there any difference between these three ways of creating an array? If not, why do the first two ways exist if they're just more code? 1: ``` var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; ``` 2: ``` var myCars=new Array("Saab","Volvo","BMW"); ``` 3: ``` var myCars=["Saab","Volvo","BMW"]; ```

Original source

Related problems