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 construct 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 = [];
function stackAdd(entry) {
stack[stackCount] = entry;
} function stackSub() {
if (stackCount > 0) {
return stack[stackCount];
} else return null;
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 = [];
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.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow