JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What is an array in JavaScript?

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.

How to create an array in JavaScript?

There are three different ways of creating an array in JavaScript.

  1. You can create an array using an array literal.
  2. Using the new keyword or Array() constructor, you can create an array.
  3. You can use Array.of() method to create an array.

Let's start the tutorial by creating an array using square brackets.

Create 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.

Create an array using a new keyword or Array() constructor

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]

Create an array using Array.of() method

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.

Recommended Posts