Over a million developers have joined DZone.

Queue Data Structure in JavaScript

DZone's Guide to

Queue Data Structure in JavaScript

A basic tutorial detailing how Queues work in JavaScript, with some code snippets to help you out.

· Web Dev Zone ·
Free Resource

Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.

JavaScript is very suitable for developing data structures and in fact in my opinion it is very easy.  Let’s us develop a “Queue” data structure in Java Script

By definition, Queue is a First-in-First-Out data structure, which means that it will maintain the insertion order. For example, if we insert 1, 2, 3 into a queue data structure, then it will output 1, 2, and 3 in the same order.

So we will develop a simple queue here.  In order to develop a queue, we can use an array. The array will hold the entire inserted item as shown below:

var arr = [];

The functionality of a Queue is that when you get an item from it, it will return the top element and remove it from the Queue. This is the default behavior of a Queue, which will put the next element on the top of the queue.

We can start with a  function called "Queue":

function Queue() {
	this.arr = [];

Also, we need two methods: one is add () and the other one is get ().

add() will insert an object into the array, which is shown below:

function add(item){

get() will get the item from the array, which is shown below:

function get() {
   return arr.splice(0,1);

Please take a look at the splice() method with arguments. This method can either remove or add elements to the array. In our case, since the first argument is 0, then it will remove elements instead of adding them. The second argument is 1, which will remove exactly one element from the array. This removal happens from the top of the array.

This way, you can develop a queue in JavaScript which can be used in many scenarios. The above piece of code can also be further extended.

You can take a look at this video for more information.

Get the senior executive’s handbook of important trends, tips, and strategies to compete and win in the digital economy.

data structure ,javascript ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}