×
☰ See All Chapters

JavaScript ES6 Array

An array is a homogenous ordered collection of elements of the same type. An array is a user-defined data type.

There are two general formats for array,

  1. Creating array using new keyword 

  2. Creating array using array literals  

Creating array using new keyword

let numArray = new Array(3);

Above statement creates array with size 6. All the elements in the array are now undefined. We can populate the array elements as below:

numArray[0] = 100;

numArray[1] = 150;

numArray[2] = 200;

We can also create array with initial values as below:

const cars = new Array("Audi", "Volvo", "BMW");

Creating array using array literals

let numArray = [1.5, 2, 0x12];

let strArray = ['Manu', 'Advith'];

In this approach we pass all array literals or values to array and size of will be the number of values we put in the array.

Accessing array element

Array elements can be accessed as array[index], where index is the position of the element in the array. Array index starts from 0. If you attempt to read an element beyond the array's size, undefined value will be returned.

let numArray = [1.5, 2, 0x12];

let strArray = ['Manu', 'Advith'];

 

let x = numArray[1]; // x = 2

let c = strArray[0]; // c = "Manu"

Size of an array can be obtained by accessing its length property.

let namArray: number[] = [1.5, 2, 0x12];

console.log(namArray.length); // prints 3

Array Destructuring

Suppose if you have to assign the first three values of array to three different variables we can do it as below:

let numArray = [1.5, 2, 0x12, 5, 3.9];

let a;

let b;

let c;

[a,b,c] = numArray;


All Chapters
Author