Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implementation of Queue in JavaScript
Following is the code to implement queue in JavaScript.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
button {
padding: 6px;
margin: 4px;
}
</style>
</head>
<body>
<h1>Implementation of queue in JavaScript.</h1>
<div class="result"></div>
<br />
<input type="text" class="enqueueVal" /><button class="enqueueBtn">
Enqueue
</button>
<button class="dequeueBtn">Dequeue</button>
<button class="Btn">Display</button>
<h3>Click on the above buttons to perform queue operations</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let enqueueBtnEle = document.querySelector(".enqueueBtn");
let dequeueBtnEle = document.querySelector(".dequeueBtn");
class Queue {
constructor() {
this.items = [];
this.length = 0;
}
}
Queue.prototype.enqueue = function (ele) {
this.items[this.length] = ele;
this.length += 1;
};
Queue.prototype.dequeue = function () {
debugger;
if (this.length === 0) {
return "Underflow: no more elements to remove";
}
tempNum = this.items[0];
this.length -= 1;
return tempNum;
};
Queue.prototype.display = function () {
debugger;
if (this.length == 0) {
return "Stack is empty";
}
for (let i = 0; i < this.length; i++) {
resEle.innerHTML += this.items[i] + " , ";
}
};
let queue1 = new Queue();
BtnEle.addEventListener("click", () => {
resEle.innerHTML = "";
queue1.display();
});
enqueueBtnEle.addEventListener("click", () => {
let ele = document.querySelector(".enqueueVal").value;
resEle.innerHTML = ele + " is added to the back of the queue";
queue1.enqueue(ele);
});
dequeueBtnEle.addEventListener("click", () => {
resEle.innerHTML =
queue1.dequeue() + " is removed from the front of queue";
});
</script>
</body>
</html>
Output

On entering some value and clicking on ‘Enqueue’ button −

On clicking the ‘Dequeue’ button −

On clicking the ‘Display’ button when the queue is not empty −

Advertisements