JavaScript Arrays – Push it real good

A quick shout to JavaScript array methods. With ECMA-262 version 5 (latest version 6), came several new methods for manipulating arrays. Lets focus on the ones that allow user to add or remove from either end of an array.

Add an item to the end of an array: push()

The push() method allows an element to be appended to the end of an existing array.

var someArray = ["itemOne", "itemTwo", "itemThree"]; 

someArray.push("itemFour");

someArray;  // someArray now contains["itemOne", "itemTwo", "itemThree", "itemFour"];

Remove an item from the end of an array: pop()

The pop() method removes the last element from an array. It also returns that removed element.

var lastItem = someArray.pop();

lastItem; // contains "itemFour";

Add an item to the beginning of an array: unshift()

The unshift() method adds an item to the front of an array

someArray.unshift("itemZero");
someArray ; // now contains ["itemZero", "itemOne", "itemTwo", "itemThree"]

Remove an item from the beginning of an array: shift()

The shift() method removes and returns an item from the front of an array

var firstItem = someArray.shift();

firstItem; // contains "itemZero"