Skip to content

Home

JavaScript Data Structures - Stack

Definition

A stack is a linear data structure that behaves like a real-world stack of items. It follows a last in, first out (LIFO) order of operations, similar to its real-world counterpart. This means that new items are added to the top of the stack and items are removed from the top of the stack as well.

JavaScript Stack visualization

The main operations of a stack data structure are:

Implementation

class Stack {
  constructor() {
    this.items = [];
  }

  push(item) {
    this.items.unshift(item);
  }

  pop(item) {
    return this.items.shift();
  }

  peek(item) {
    return this.items[0];
  }

  isEmpty() {
    return this.items.length === 0;
  }
}
const stack = new Stack();

stack.push('apples');
stack.push('oranges');
stack.push('pears');

stack.isEmpty();    // false

stack.peek();       // 'pears'

stack.pop();        // 'pears'
stack.pop();        // 'oranges'
stack.pop();        // 'apples'

stack.isEmpty();    // true

More like this

Start typing a keyphrase to see matching snippets.