How to Creating javascript array

Creating javascript array

JavaScript provides you with two ways to create an array. The first one is to use the Array constructor as follows:

let scores = new Array();

The scores array is empty i.e. it holds no element.

If you know the number of elements that the array will hold, you can create an array with an initial size as shown in the following example:

let scores = Array(10);

To create an array with some elements, you pass the elements as a comma-separated list into the Array() constructor.

For example, the following creates the scores array that has five elements (or numbers):

let scores = new Array(9,10,8,7,6);

It’s important to notice that if you use the array constructor to create an array and pass into a number, you are creating an array with an initial size.

However, when you pass a value of another type like string into the Array() constructor, you create an array with an element of that value. For example:

let athletes = new Array(3); // creates an array with initial size 3
let scores = new Array(1, 2, 3); // create an array with three numbers 1,2 3
let signs = new Array('Red'); // creates an array with one element 'Red'

JavaScript allows you to omit the new operator when you use the array constructor. For example, the following statement creates the artists array.

let artists = Array();

In practice, you’ll rarely use the Array() constructor to create an array.

The more preferred way to create an array is to use the array literal notation:

let arrayName = [element1, element2, element3, ...];

The array literal form uses the square brackets [] to wrap a comma-separated list of elements.

The following example creates the colors array that hold three strings:

let colors = ['red', 'green', 'blue'];

To create an empty array, you use square brackets without specifying any element like this:

let emptyArray = [];