Stacks

All about stacks in Javascript


A stack follows Last-In First-Out (LIFO) principle. That is, the last element added to the stack will be the first one to be removed.

Thus, the following arrays methods helps to build a stack:

  • push
  • pop

push()

Adds an element in-place at the top of the stack (end of they array).

const arr = [1,2,3,4]
arr.push(5);
arr // -> [1,2,3,4,5]

pop()

Removes an element in-place from the top of the stack.

const arr = [1,2,3,4]
arr.pop()
arr // -> [1,2,3]