How will you implement stack and queue with JavaScript?

Feb 21, 2018

Stack

stack is already implemented in JavaScritp array. you can simply call push and pop method.

var newStack = [];

//push

newStack.push(1);

newStack.push(2);

newStack.push(3);

//pop

newStack.pop(); //3

newStack.pop(); //2

newStack.pop(); //1

 

Queue

Queue is pretty much same. other than calling pop you will use shift method to get the element in the front side of your array.

var newQueue = [];

//push

newQueue.push(1);

newQueue.push(2);

newQueue.push(3);

 

//shift

newQueue.shift(); //1

newQueue.shift(); //2

newQueue.shift(); //3

The question and answer are referred from thatjsdude