Creating a Stack in Javascript

To create a stack in Javascript simply use an array.

Arrays in javascript already contain both push and pop methods necessary to manipulate a stack.


//Example:
var stack = [];

//add items into the stack
stack.push("A"); //append "A" to the array
stack.push("B"); //append "B" to the array
stack.push("C"); //append "C" to the array

//the stack array will look like this = ["A", "B", "C"]

//now remove items out of the stack in a LIFO fashion
var item = stack.pop(); // item = "C"
//stack = ["A", "B"]
item = stack.pop(); //item = "B"
//stack = ["A"]
item = stack.pop(); //item = "A"
//stack = []

The method pop() removes the last element in the array. This creates a LIFO (Last in, first out) effect.

If you want to create a stack object with more methods, like peak and size for instance … ¬†One of the ways to do it is to create your own stack object. See code below:


function Stack(){
   this.stack = [];
}

Stack.prototype.pop = function(){
   return this.stack.pop();
}

Stack.prototype.push = function(item){
   this.stack.push(item);
}

Stack.prototype.peak = function(){
   var len = this.stack.length;
   return (this.stack[len-1] !==null)? this.stack[len-1] : null;
}

Stack.prototype.size = function(){
   return this.stack.length;
}


Posted on: September 25th, 2013 by Stephani

Leave a Reply