How to use array as stack in JavaScript – JavaScript Array

4 years ago Lalit Bhagtani 0

JavaScript Array as Stack

In this tutorial, we will learn about how to use array as stack in JavaScript. Stack is linear data structure, which follows the Last In First Out (LIFO) principle. The last element inserted into a stack is the first element removed from it. The Stack data structure provides the following operations:

  1. push(N) :- It insert element N onto the top of the stack.
  2. pop() :- It removes and returns the element from the top of the stack.

JavaScript Array as Stack

Arrays push & pop method :-

Array’s push and pop method can replicate the push and pop operation of the stack data structure. Array’s push method inserts an element at the end of the array and Array’s pop method removes and returns the last element of the array.

Syntax :-

Push Operation :- Array.push(E)
Pop Operation :- Array.pop()

Let’s see the example :- 

<script>
var array = [1, 2, 3];

array.push(4);
console.log(array);

var element = array.pop();
console.log(element);
</script>

Arrays unshift & shift method :-

Array’s unshift and shift method can replicate the push and pop operation of the stack data structure. Array’s unshift method inserts an element at the beginning of the array and Array’s shift method removes and returns the first element of the array.

Syntax :-

Push Operation :- Array.unshift(E)
Pop Operation :- Array.shift()

Let’s see the example :- 

<script>
var array = [2, 3, 4];

array.unshift(1);
console.log(array);

var element = array.shift();
console.log(element);
</script>

References :- 

  1. Array push Docs
  2. Array pop Docs
  3. Array shift Docs
  4. Array unshift Docs

That’s all for how to use array as stack in JavaScript. If you liked it, please share your thoughts in comments section and share it with others too.