Queue Data Structure in JavaScript

Level 5493 keystrokes

Implements a FIFO (first in, first out) queue on top of an array. After enqueuing "first", "second" and "third" it prints the front ("first"), two dequeues ("first", then "second"), the size (1) and the new front ("third").

JavaScript code

// A queue class: items join at the end and leave from the front
1class Queue {
// Starts with an empty array of items
2 constructor() { this.items = []; }
// Adds an item at the back of the queue
3 enqueue(item) { this.items.push(item); }
// shift removes and returns the front item, the oldest one
4 dequeue() { return this.items.shift(); }
// Returns the front item without removing it
5 front() { return this.items[0]; }
// true when the queue has no items
6 isEmpty() { return this.items.length === 0; }
// Returns the number of items
7 size() { return this.items.length; }
8}
9
// Creates an empty queue
10const queue = new Queue();
// Adds three items; "first" is at the front, "third" at the back
11queue.enqueue("first");
12queue.enqueue("second");
13queue.enqueue("third");
// Prints first; the item stays in the queue
14console.log(queue.front());
// Removes and prints first, the item added first
15console.log(queue.dequeue());
// Removes and prints second
16console.log(queue.dequeue());
// Prints 1, because only "third" is left
17console.log(queue.size());
// The front is now third
18console.log(queue.front());

Output

first
first
second
1
third
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • .× 23
  • (× 22
  • )× 22
  • ;× 15
  • {× 7
  • }× 7
  • "× 6
  • =× 5
  • [× 2
  • ]× 2

More JavaScript examples at level 5

← JavaScript typing practice