Ninja secret of javascript array

power of array

Primitive variable just store one value. Lot of time it’s vary difficult to manage multiple variable so avoid this problem we need storage to store multiple element inside one variable. So basically array is an ordered series or arrangement. For more details you can see MDN. But it’s vary useful to maintain multiple values at once.

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 way to add and remove element from array. The way have different 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

You May Also Like

About the Author: admin