An array is a way of storing multiple values in a single place. You can think of an array as a list of values, and those values could be strings, numbers, booleans, objects, arrays or their combination.
There are three different ways of creating an array in JavaScript.
new
keyword or Array()
constructor, you can create an array.Array.of()
method to create an array.Let's start the tutorial by creating an array using square brackets.
Square brackets represent array literals. Inside square brackets, you pass comma-separated values. The values can be strings, numbers, booleans, objects or a combination of different types of values.
let fruits = ["Mangoes", "Apples", "Grapes"]; let squareOfNumbers = [4, 9, 25, 36]; console.log('Fruits array: ', fruits); console.log('squareOfNumbers array: ', squareOfNumbers);
In the above code, two arrays are created, fruits
and squareOfNumbers
.
All the elements of the fruits
array are strings, whereas all the elements of the squareOfNumbers
array are numbers.
Output
Fruits array: ["Mangoes", "Apples", "Grapes"] squareOfNumbers array: [4, 9, 25, 36]
Note: Array literals are considered to be the simplest way of creating an array in JavaScript.
new
keyword helps you to create an array. You can pass any number of arguments to the Array()
constructor. But when you pass a single number as an argument to the constructor, then an empty array is created whose length
property is equal to that number. All the elements of the array are set to undefined
.
On the other end, if you pass nothing to the constructor, then an empty array is created whose length
property is equal to zero.
let indoorGames = new Array("Chess", "Table Tennis", "Jenga"); console.log(indoorGames); //["Chess", "Table Tennis", "Jenga"] let arr = new Array(4); console.log(arr); //[undefined, undefined, undefined, undefined]
Array.of()
method creates an array from the arguments passed to it. You can pass any number of arguments to Array.of()
method.
let indoorGames = Array.of("Chess", "Table Tennis", "Jenga", "Scrabble"); console.log(indoorGames);
Output
["Chess", "Table Tennis", "Jenga", "Scrabble"]
In the above code, an array is created that has four elements. All the elements of this array are string. Similarly, you can create an array of numbers and other types.