JavaScript Arrays

The primitive variable just stores one value. A lot of time it’s very difficult to manage multiple variables so to avoid this problem we need storage to store multiple elements inside one variable. So basically javascript array is an ordered series or arrangement. For more details, you can see MDN. But it’s very useful to maintain multiple values at once.

Array is an ordered series or arrangement.

It's all about one and two dimention

Creation or Declaration


var arr = []; //empty array
var arr = [1, 2, 3, 4, 5] //array with integer elements
var fruits = ["Apple", "Mango", "Orange"]; //array with string elements

Get length


console.log(arr.length); //5

Get value


console.log(arr[2]); //3

Reset value


arr.length = 0;
or
arr.length = []; 

Accessing all value



for (var i = 0, len = fruits.length; i < len; i++) {
    console.log(fruits[i]);
}
// Apple, Mango, Orange

Find type


// First solution
Array.isArray(fruits);     // returns true

//Second solution
fruits instanceof Array    // returns true

//Third solution
function isArr(coll) {
    return coll.constructor.toString().indexOf("Array") > -1;
}

isArr(fruits); // returns true

Add and remove element

We have three ways to add and remove an element from an array. We have different use cases.



var arr = [];

//Frist way
arr[0] = "zeroth";
console.log(arr); // zeroth

//Second way - work as stack format value add after last index of array
arr.push("first");
console.log(arr); // zeroth, <b>first</b>

//Third way - work as queue format value add before zeroth index
arr.unshift("second");
console.log(arr); // <b>second</b>, zeroth, first

Also see: Variables and data types in javascript

About the Author: Pankaj Bisht