JS - Arrays

by Vijay Venkatan

JavaScript

var myArrayLiteral = [1,2,3];
var myArrayConstructed = new Array(1,2,3);

console.log(myArrayLiteral);
console.log(myArrayConstructed);

// stick to [] to access, since arr.0 will fail
console.log(myArrayLiteral[0]);

// Arrays have a length property
console.log(myArrayLiteral.length);

// Arrays have methods to play with
console.log("Is this an array? ", Array.isArray(myArrayLiteral));

var lastEl = myArrayLiteral.pop();
var firstEl = myArrayLiteral.shift();
console.log(firstEl, lastEl, myArrayLiteral);

myArrayLiteral.push(lastEl);
myArrayLiteral.unshift(firstEl);
console.log(myArrayLiteral);

// Iterating over an array
for (var i=0; i < myArrayLiteral.length; i++) {
     console.log(myArrayLiteral[i]);   
}

// In ES5 you can use Array.forEach()
myArrayLiteral.forEach(function(el, i, originalArray) {
   console.log(el, i, originalArray); 
});