W3docs

How to Declare and Initialize an Array in JavaScript

Read this tutorial and learn the two basic methods of declaring and initializing an Array in JavaScript. Also, read about the differences of the methods.

JavaScript allows declaring an Array in several ways. Let's consider two most common ways: the array constructor and the literal notation.

The new Array() Constructor

The <kbd class="highlighted">Array()</kbd> constructor creates Array objects. You can declare an array with the "new" keyword to instantiate the array in memory. Here’s how you can declare new <kbd class="highlighted">Array()</kbd> constructor:

  • let x = new Array(); - an empty array
  • let x = new Array(10,20,30); - three elements in the array: 10,20,30
  • let x = new Array(10); - ten empty elements in array: ,,,,,,,,,
  • let x = new Array('10'); - an array with 1 element: ‘10’

Let's see an example where the array has five elements:

Javascript Array constructor

javascript— editable

The new keyword only complicates the code. It can also produce some unexpected results.

The Literal Notation

Instead of <kbd class="highlighted">new Array()</kbd> , you can use square brackets []. Using square brackets is called the "array literal notation":

  • let x = []; - an empty array
  • let x = [10]; - initialized array
  • let x = [10,20,30]; - three elements in the array: 10,20,30
  • let x = ["10", "20", "30"]; - declares the same: ‘10’,’20’,’30’

Javascript array use square brackets

javascript— editable

Line breaks and spaces are not important. The declaration can span multiple lines like in this example:

Javascript array declaration can span multiple lines

javascript— editable

The Difference Between Array() and []

Using Array literal notation if you put a number in the square brackets it will return the number while using new <kbd class="highlighted">Array()</kbd> if you pass a number to the constructor, you will get an array of that length.

you call the <kbd class="highlighted">Array()</kbd> constructor with two or more arguments, the arguments will create the array elements. If you only invoke one argument, the argument initializes the length of the new array; the new array's elements are not initialized.