Course
Introduction
Print Hello WorldAdd Two NumbersFind the Square RootCalculate the Area of a TriangleSwap Two VariablesConvert Kilometers to MilesConvert Celsius to FahrenheitWork With ConstantsWrite to ConsoleControl Flow
Solve Quadratic EquationCheck if a number is Positive, Negative, or ZeroCheck if a Number is Odd or EvenFind the Largest Among Three NumbersCheck Prime NumberPrint All Prime Numbers in an IntervalFind the Factorial of a NumberDisplay the Multiplication TablePrint the Fibonacci SequenceCheck Armstrong NumberFind Armstrong Number in an IntervalMake a Simple CalculatorFind the Sum of Natural NumbersCheck if the Numbers Have Same Last DigitFind HCF or GCDFind LCMFind the Factors of a NumberDisplay Fibonacci Sequence Using RecursionFunctions
Generate a Random NumberFind Sum of Natural Numbers Using RecursionGuess a Random NumberFind Factorial of Number Using RecursionConvert Decimal to BinaryFind ASCII Value of CharacterSet a Default Parameter Value For a FunctionCheck If a Variable is of Function TypePass Parameter to a setTimeout() FunctionPerform Function OverloadingPass a Function as ParameterArrays and Objects
Shuffle Deck of CardsCreate Objects in Different WaysRemove a Property from an ObjectCheck if a Key Exists in an ObjectClone a JS ObjectLoop Through an ObjectMerge Property of Two ObjectsCount the Number of Keys/Properties in an ObjectAdd Key/Value Pair to an ObjectConvert Objects to StringsReplace all Instances of a Character in a StringRemove Specific Item From an ArrayCheck if An Array Contains a Specified ValueInsert Item in an ArrayAppend an Object to an ArrayCheck if An Object is An ArrayEmpty an ArrayAdd Element to Start of an ArrayRemove Duplicates From ArrayMerge Two Arrays and Remove Duplicate ItemsSort Array of Objects by Property ValuesCreate Two Dimensional ArrayExtract Given Property Values from Objects as ArrayCompare Elements of Two ArraysGet Random Item From an ArrayPerform Intersection Between Two ArraysSplit Array into Smaller ChunksCheck If A Variable Is undefined or nullIllustrate Different Set OperationsStrings
Check Whether a String is Palindrome or NotSort Words in Alphabetical OrderReplace Characters of a StringReverse a StringCheck the Number of Occurrences of a Character in the StringConvert the First Letter of a String into UpperCaseCount the Number of Vowels in a StringCheck Whether a String Starts and Ends With Certain CharactersReplace All Occurrences of a StringCreate Multiline StringsFormat Numbers as Currency StringsGenerate Random StringCheck if a String Starts With Another StringTrim a StringCheck Whether a String Contains a SubstringCompare Two StringsEncode a String to Base64Replace All Line Breaks withGet File ExtensionGenerate a Range of Numbers and CharactersRemove All Whitespaces From a TextMiscellaneous
Display Date and TimeCheck Leap YearFormat the DateDisplay Current DateCompare The Value of Two DatesCreate Countdown TimerInclude a JS file in Another JS fileGenerate a Random Number Between Two NumbersGet The Current URLValidate An Email AddressImplement a StackImplement a QueueCheck if a Number is Float or IntegerGet the Dimensions of an ImageConvert Date to NumberJavaScript Program to Implement a Queue
To understand this example, you should have the knowledge of the following JavaScript programming topics:
A queue is a data structure that follows the First In First Out (FIFO) principle.
The first element added to the queue is the first one to be removed. This is like being in a queue to get a movie ticket. The first one in the queue gets the ticket first.
Example: Implement Queue
// program to implement queue data structure
class Queue {
constructor() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
//adds a new element
enqueue(element) {
this.items[this.tailIndex] = element;
this.tailIndex++;
}
//removes an element from head of the queue
dequeue() {
let removedElement = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return removedElement;
}
//shows the head element of the queue
peek() {
let peekElement = this.items[this.headIndex];
return peekElement;
}
//shows the number of items in queue
size() {
return this.tailIndex - this.headIndex;
}
//checks if queue is empty or not
isEmpty() {
if (this.tailIndex - this.headIndex == 0) {
return true;
}
else {
return false;
}
}
//empty the queue
clear() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
}
let queue = new Queue();
// add items to queue
queue.enqueue(8);
queue.enqueue(6);
queue.enqueue(4);
queue.enqueue(2);
console.log("Queue after adding items: ");
console.log(queue.items);
// remove the first item
queue.dequeue();
console.log("Queue after deleting the first item:");
console.log(queue.items);
// show the first item
console.log("First item of the queue = " + queue.peek());
// empty the queue
queue.clear();
console.log("After clearing the queue: ");
console.log(queue.items);
Output
Queue after adding items:
{ '0': 8, '1': 6, '2': 4, '3': 2 }
Queue after deleting the first item:
{ '1': 6, '2': 4, '3': 2 }
First item of the queue = 6
After clearing the queue:
{}
In the above program, the queue data structure is implemented using the object. The Queue
class is created to implement the queue data structure. The class includes methods like enqueue()
, dequeue()
, peek()
, isEmpty()
, size()
, and clear()
.
A Queue
object is created using a new
operator and various methods are accessed through the object.
- Initially,
this.items
is an empty object which is treated as a queue. - The
enqueue()
method adds elements to the queue. - The
dequeue()
method removes the first element from the queue. - The
peek()
method returns the first element from the queue. - The
size()
method shows the total number of elements in the queue. - The
isEmpty()
method returns a boolean checking if the queue is empty or not. - The
clear()
method clears and resets the queue.
Also Read: