How to Declare and Initialize an Array in JavaScript

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 Array() 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 Array() 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:

let arr = new Array (1, 2, 3, 4, 5);
console.log(arr);

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

The Literal Notation

Instead of new Array() , 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’
let arr = ["1", "2", "3"];
console.log(arr);

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

let arr = [
  "1",
  "2",
  "3"
];
console.log(arr);

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 Array() if you pass a number to the constructor, you will get an array of that length.

you call the Array() 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.


Do you find this helpful?

Related articles