Categories
JavaScript Tutorials

Stack Methods

The insertion (called a push) and removal (called a pop) of items in a stack occur at only one point: the top of the stack. Javascript arrays provide push() and pop() specifically to allow stack-like behavior.

  • The push() method accepts any number of arguments and adds them to the end of the array, returning the array’s new length. 
  • The pop() method, on the other hand, removes the last item in the array, decrements the array’s length, and returns that item. 

Consider this example:

var colors = [ ]; //create an array
var count = colors.push("red", "green"); //push two items
alert(count); //2
count = colors.push("black"); //push another item on
alert(count); //3
var item = colors.pop(); //get the last item
alert(item); //"black"
alert(colors.length); //2

In this code, an array is created for use as a stack (note that there’s no special code required to make this work; push() and pop() are default methods on arrays). First, two strings are pushed onto the end of the array using push(), and the result is stored in the variable count (which gets the value of 2). Then, another value is pushed on, and the result is once again stored in count. Because there are now three items in the array, push() returns 3. When pop() is called, it returns the last item in the array, which is the string “black”. The array then has only two items left. The stack methods may be used in combination with all of the other array methods as well, as in this example:

var colors = ["red", "blue"];
colors.push("brown"); //add another item
colors[3] = "black"; //add an item
alert(colors.length); //4
var item = colors.pop(); //get the last item
alert(item); //"black"

Here, an array is initialized with two values. A third value is added via push(), and a fourth is added by direct assignment into position 3. When pop() is called, it returns the string “black”,

which was the last value added to the array.

Examples

Create an array of elements and then add three elements to the end of the array.

var flowers = ['Rose', 'Marigold'];
flowers.push('Lily', 'Lotus', 'Sunflower');

Create an array of elements and then remove the last element of the array.

var birds = ['Peacock', 'Owl', 'Swan'];
birds.pop();

Create an array of elements and then remove the last element of the array and then print the removed element in the console.

var food = ['burger', 'pizza', 'momo'];
var removed = food.pop();
console.log(removed);