Creating a Queue in Javascript

To create a queue in javascript simply use an array.

Arrays in javascript already contain both queue and dequeue methods necessary to manipulate a queue. They are just not called queue and dequeue.

To enqueue into a queue, simply use the method push.
To dequeue from a queue, simply use the method shift.

//Example:
var queue = [];

//enqueue:
queue.push("A");
queue.push("B");
queue.push("C");

//queue now contains ["A", "B", "C"]

//dequeue
var item = queue.shift(); //item = "A"
//queue = ["B", "C"]

item = queue.shift(); //item = "B"
//queue = ["C"]

item = queue.shift(); //item = "C"
//queue = []

The method shift removes the first item in the array. Creating a FIFO (First in, first out) effect.

If you want to create  your own queue object and actually have queue and dequeue methods you can do it the following way:


function Queue(){
   this.queue = [];
}

Queue.prototype.enqueue = function(item){
   this.queue.push(item);
}

Queue.prototype.dequeue = function(){
   return this.queue.shift();
}

Queue.prototype.size = function(){
   return this.queue.length;
}

Queue.prototype.peak = function(){
   return (this.queue[0] !== null) ? this.queue[0] : null;
}


Posted on: September 25th, 2013 by Stephani

Leave a Reply