1. Home
  2. Computing & Technology
  3. JavaScript

Stacks

Join the Discussion

Questions? Comments?

Related Constructs

Queues

One construct that Javascript does not at first glance appear to support is that of the Stack. For those of you unfamiliar with the idea of stacks, imagine you have a number of plates. You can put the plates one on top of the other to form a stack of plates. It doesn't matter how many plates that are already in the stack when you add another plate to the stack and as long as there is at least one plate still in the stack it doesn't matter how many plates are there when you want to take one from the stack.

A stack works on the principle of Last In - First Out (LIFO) since (as you can imagine from our example) removing a plate other than the top one on the stack is not very easy without first removing those plates above it in the stack.

You might think that the easiest way of creating an equivalent contruct is to create an Array and just keep track of how many entries that the array is supposed to contain. For example:

var stackCount = 0;
var stack = new Array();
function stackAdd(entry) {
stack[stackCount] = entry;
stackCount++;
}
function stackSub() {
if (stackCount > 0) {
stackCount--;
return stack[stackCount];
} else return null;
}
...
stackAdd(entry1);
var entry2 = stackSub();

In fact Arrays in Javascript contain built-in methods that make all this coding unnecessary. We can achieve the exact same result using the following much simpler code which keeps track of which entry in the array is being used automatically.

var stack = new Array();
...
stack.push(entry1);
var entry2 = stack.pop();

Using push() always adds a new entry onto the end of an array. Using pop() always retrieves the last entry from an array as well as removing that entry from the array. This removes the need for us to keep track separately of how many entries our array contains when we are using it like this.

Explore JavaScript
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2010 About.com, a part of The New York Times Company.

All rights reserved.