Tuesday, 24 April 2018

Arrays in JavaScript

JavaScript arrays are different from the arrays of some languages such as C,C++ and Java. In JavaScript arrays can store multiple elements of different types unlike C++ or C in which arrays are used to store the multiple elements of the same data type. In JavaScript array is simply a list of elements and used to access them by a single variable.

Example: 

let A=[2,3,"This","is","string"];

In this example you can notice that array A consist of elements of differnt types.

Declaration of Array:

In JavaScript, arrays can be declared in two ways.

//Method 1
var arr=["This","is","a","string"];

//Initializing after declaration
arr[4]="javascript";

//Method 2
var arr=new Array("This","is","a","String");

//You can also declare an array of the given size of undefined elements
var arr=new Array(6);



Accessing array elements: 

 Like other languages, You can access JavaScript arrays using indexing which starts from 0.

Example

arr[0]="This";
arr[1]="is";
arr[2]="a";
arr[3]="string";


The length of a JavaScript array can be retrived by using length property.

 Example:

//arr.length will give you the length of the array.

var arr=["Guru","Tegh","Bahadur","Institute","Of","Technology"];
console.log(arr.length);


EmoticonEmoticon