Array in JavaScript

Array object in javascript lets you to store keyed collections of values into a single variable with indexing start with 0. Type of each and every value can be same either number, string or float. Here in this article we will learn all possible ways to create an array.

Declaration Syntax:

There are two syntax for creating an empty array:

let a = new Array(); let a = []; //OR var a = new Array(); var a = [];

Almost all the time, the second syntax is used. We can initialize an array by adding its values with in  square brackets separated by a comma (,) as shown below.

Array With Initialization:

let colors = ["Red", "Green", "Blue"];

We can access elements of an array by its index starting with zero(0).

Accessing Array with array index:

colors[0]; // will return Red colors[1]; // will return Green colors[2]; // will return Blue

Replacing Array Element:

We can replace an element of array as follows.

colors[1] = "Orange"; colors[1]; // will return Orange

Adding new Element in array:

We can add new value in an array as follows.

colors[3] = "Cyan"; colors; // will return (4) ["Red", "Green", "Blue", "Cyan"]

Length or Count elements of Array:

a.length; // return 4

Different Types of Elements inside array:

An array can store elements of any type.

var b = [12,"ss",45.56,true, {}, [], function a(){}]; b; // return (7) [12, "ss", 45.56, true, {…}, Array(0), ƒ]

Multidimensional arrays:

Arrays can have items that are also arrays. We can use it for multidimensional arrays, to store matrices:

let matrix = [   [1, 2, 3],   [4, 5, 6],   [7, 8, 9] ]; matrix; // return [Array(3), Array(3), Array(3)]

Array iteration:

We can access each and every element of array by using any loop with index and length property as follows.

var a = ["Red", "Green", "Blue"]; for(var i=0; i<a.length; i++){ console.log(a[i]); } //OUTPUT: //Red //Green //Blue

Empty Array:

We can create empty array or delete all collections of its elements as follows.

//Empty array declaration. var a = []; //Initialization of array. for(var i=0; i<5; i++){ a[i]=i; } //Clear or delete all elements of an Array  a = [];

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories