[javascript] What is the way of declaring an array in JavaScript?

I'm just learning JavaScript and it seems like there are a number of ways to declare arrays.

  1. var myArray = new Array()
  2. var myArray = new Array(3)
  3. var myArray = ["apples", "bananas", "oranges"]
  4. var myArray = [3]

What are their difference, and what are the preferred ways?

According to this website the following two lines are very different:

var badArray = new Array(10); // creates an empty Array that's sized for 10 elements
var goodArray= [10];          // creates an Array with 10 as the first element

As you can see these two lines do two very different things. If you had wanted to add more than one item then badArray would be initialized correctly since Javascript would then be smart enough to know that you were initializing the array instead of stating how many elements you wanted to add.

Is what the authors trying to say is Array(10) creates an array with precisely 10 elements and [10] creates an array of undefined size with the 0th element being 10? Or what does this mean?

This question is related to javascript arrays

The answer is


In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.

Be careful when using new Array().

var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]

The preferred way is using the [] syntax.

var x = []; // array of size 0
var y = [10] // array of size 1: [1]

var z = []; // array of size 0
z[2] = 12;  // z is now size 3: [undefined, undefined, 12]

If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length); is appropriate.

eg-

String.prototype.repeat= function(n){
    n= n || 1;
    return Array(n+1).join(this);
}

To declare it:

var myArr = ["apples", "oranges", "bananas"];

To use it:

document.write("In my shopping basket I have " + myArr[0] + ", " + myArr[1] + ", and " + myArr[2]);

There are a number of ways to create arrays.

The traditional way of declaring and initializing an array looks like this:

var a = new Array(5); // declare an array "a", of size 5
a = [0, 0, 0, 0, 0];  // initialize each of the array's elements to 0

Or...

// declare and initialize an array in a single statement
var a = new Array(0, 0, 0, 0, 0);