Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 565
Celeritas Avatar asked Jul 09 '12 21:07

Celeritas


People also ask

How do you declare an array in JavaScript?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

How many ways can you declare an array in JavaScript?

Array Initialization An array in JavaScript can be defined and initialized in two ways, array literal and Array constructor syntax.

What is the correct way of declaring an array?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};


1 Answers

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] 
like image 181
Rocket Hazmat Avatar answered Sep 19 '22 08:09

Rocket Hazmat