Javascript - Array Queue Methods: shift() and unshift()

Introduction

Queues restrict access in a first-in-first-out (FIFO) data structure.

A queue adds items to the end of a list and retrieves items from the front of the list.

Because the push() method adds items to the end of an array, all that is needed to emulate a queue is a method to retrieve the first item in the array.

The array method for this is called shift(), which removes the first item in the array and returns it, decrementing the length of the array by one.

Using shift() in combination with push() allows arrays to be used as queues:

Demo

var colors = new Array();                      //create an array
var count = colors.push("red", "green");       //push two items
console.log(count);  //2

count = colors.push("black");                  //push another item on
console.log(count);  //3

var item = colors.shift();                     //get the first item
console.log(item);   //"red"
console.log(colors.length);  //2

Result

This example creates an array of three colors using the push() method.

ECMAScript unshift() method of arrays adds any number of items to the front of an array and returns the new array length.

By using unshift() in combination with pop(), it's possible to emulate a queue in the opposite direction.

Demo

var colors = new Array();                      //create an array
var count = colors.unshift("red", "green");    //push two items
console.log(count);  //2

count = colors.unshift("black");               //push another item on
console.log(count);  //3
var item = colors.pop();                     //get the first item
console.log(item);   //"green"
console.log(colors.length);  //2

Result