Array in JavaScript

Array in JavaScript

An array is a collection of elements that use the common name to store all the elements. Array always start from Memory Location Zero. It is lengthy process to store huge elements in a separate variable; Arrays solve this problem by storing all the elements into one variable.

Types of Array

  1. One dimensional Array
  2. Multidimensional Array

One dimensional Array

Creating an Array

Array can easily be created in JavaScript either enclosing a comma-separated list of values in square brackets ([]), or using the Array () constructor.

Syntax

  • let arr = new Array();
  • let arr = [];

Example

  • var myArray = [element0, element1, …, elementN];
  • var myArray = new Array(element0, element1, …, elementN);

Accessing the Elements of an Array

Array can easily have accessed by their index using the square bracket notation and index is a number that represents an element’s position in an array.

Syntax

Array_name[index]

Example

myArray[0];

Example to call individual elements

let loops = [“for”, “while”, “do-while”];
alert (loops [1]);

Example to call all elements

let loops = [“for”, “while”, “do-while”];
for (let i = 0; i < loops.length; i++) {
alert( loops [i] );
}

We can also use for..of and for.. in loop in javascript to iterate all the elements

let loops = [“for”, “while”, “do-while”];
for (let loop of loops) {
alert( loop);
}
let loops = [“for”, “while”, “do-while”];
for (let key in loops) {
alert( loops [key] );
}

Multidimensional arrays

Multidimensional array is an array which have array inside array.

let matrix = [ [11, 42, 63], [47, 54, 68], [57, 87, 94]];

alert( matrix[1][1] );

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*