Javascript - Array Stack Methods: push() pop()

Introduction

An array object can act like a stack, which restrict the insertion and removal of items.

A stack is referred to as a last-in-first-out (LIFO) structure.

The most recently added item is the first one removed.

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.

ECMAScript 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.

Demo

var colors = new Array();                      //create an array
var count = colors.push("red", "green");       //push two items
console.log(count);  //2

count = colors.push("black");                  //push another item on
console.log(count);  //3

var item = colors.pop();                       //get the last item
console.log(item);   //"black"
console.log(colors.length);  //2

Result

In this code, an array is created for use as a stack.

First, two strings are pushed onto the end of the array using push(), and the result is stored in the variable count.

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:

Demo

var colors = ["red", "blue"];
colors.push("brown");              //add another item
colors[3] = "black";               //add an item
console.log(colors.length);  //4

var item = colors.pop();           //get the last item
console.log(item);  //"black"

Result

Exercise