Stack Data Structure with JavaScript Array Methods

Stacks are a pretty basic and commonly used Data Structure, you might be using often and never realized it. We will use Array’s for Stacks in JavaScript, there are already build in Array methods that help you out with this. Let’s talk about Stack Data Structure in JavaScript.

Stacks

The meaning of stack is basically a pile of objects, consider you’ve 3 books, A, B, and C. When we place the book on top of each other it’s basically a stack. We will place book A first then B on top of A and finally, C on the top of B. Now if we want to empty the stack we will obviously pick C then B and finally A.

So the order is pretty clear, the last-placed book will get out first. It’s called LIFO (last in first out) or FILO (first in last out) and it’s the idea behind the stack.

Let’s see how we can implement Stack using JavaScript Array’s, to make life easy JavaScript provides ready to use Array methods to implement a stack, these methods are,

  1. push(), this will push a value into the stack in the last position
  2. pop(), this will remove the last inserted value

let’s see examples,

// we will initialize a empty array
const bookStack = [];
// push book into array
bookStack.push('A');    // 1
bookStack.push('B');    // 2
bookStack.push('C');    // 3
// check array
console.log(bookStack);    // ['A', 'B', 'C']

// using pop method
bookStack.pop(); //    "C"
bookStack.pop(); //    "B"
bookStack.pop(); //    "A"

console.log(bookStack);    // []

As we can see push() inserts value at last index and pop() removes the last inserted index. In a nutshell that’s the Stack Data Structure.

Similar Articles:

Useful JavaScript Array methods you should know – Part I

Leave a Reply

Your email address will not be published. Required fields are marked *