FCC - JS Array .push() and .shift() and unshift()
by vanduzled
JavaScript
// Setup
var myArray = [["John", 23], ["cat", 2]];
// pushes an array to an existing array
myArray.push(["dog",3]);
//[ [ 'John', 23 ], [ 'cat', 2 ], [ '3', 3 ] ]
//Another way to change the data in an array is with the .pop() function.
var myArray = [["John", 23], ["cat", 2]];
// removes the last array from an existing array and asign it to a variable
var removedFromMyArray = myArray.pop();
//[ 'cat', 2 ]
//That's where .shift() comes in. It works just like .pop(), except it removes the first element instead of the last.
var myArray = [["John", 23], ["dog", 3]];
// removes the first array from an existing array and asign it to a variable
var removedFromMyArray = myArray.shift();
//removedFromMyArray = [ 'John', 23 ]
//.unshift() works exactly like .push(), but instead of adding the element at the end of the array,
var myArray = [["John", 23], ["dog", 3]];
myArray.shift();
// unshift() adds the element at the beginning of the array.
myArray.unshift(["Paul", 35]);
//[ [ 'Paul', 35 ], [ 'dog', 3 ] ]