How to use array as queue in JavaScript – JavaScript Array

4 years ago Lalit Bhagtani 0

JavaScript Array as Queue

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

  1. enqueue(N) :- It insert element N to the back of the queue.
  2. dequeue() :- It removes and returns the element from the front of the queue.

JavaScript Array as Queue

Arrays push & shift method :-

Array’s push and shift method can replicate the enqueue and dequeue operation of the queue data structure. Array’s push method inserts an element at the end of the array and Array’s shift method removes and returns the first element of the array.

Syntax :-

Enqueue Operation :- Array.push(E)
Dequeue Operation :- Array.shift()

Let’s see the example :- 

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

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

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

Arrays unshift & pop method :-

Array’s unshift and pop method can replicate the enqueue and dequeue operation of the queue data structure. Array’s unshift method inserts an element at the beginning of the array and Array’s pop method removes and returns the last element of the array.

Syntax :-

Enqueue Operation :- Array.unshift(E)
Dequeue Operation :- Array.pop()

Let’s see the example :- 

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

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

var element = array.pop();
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 queue in JavaScript. If you liked it, please share your thoughts in comments section and share it with others too.