Stack Data Structure in JavaScript

Level 5468 keystrokes

Implements a LIFO (last in, first out) stack on top of an array. After pushing 1, 2 and 3 it prints peek (3), two pops (3, then 2), the size (1) and isEmpty (false).

JavaScript code

// A stack class; the end of the array is the top of the stack
1class Stack {
// Starts with an empty array of items
2 constructor() { this.items = []; }
// Puts an item on top of the stack
3 push(item) { this.items.push(item); }
// Removes and returns the top item, the one pushed last
4 pop() { return this.items.pop(); }
// Returns the top item without removing it
5 peek() { return this.items[this.items.length - 1]; }
// true when the stack 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 stack
10const stack = new Stack();
// Pushes 1, 2, 3; the stack is now [1, 2, 3] with 3 on top
11stack.push(1);
12stack.push(2);
13stack.push(3);
// Prints the top item, 3, which stays on the stack
14console.log(stack.peek());
// Pops and prints 3; the stack is now [1, 2]
15console.log(stack.pop());
// Pops and prints 2; the stack is now [1]
16console.log(stack.pop());
// Prints 1, because one item is left
17console.log(stack.size());
// Prints false, since 1 is still on the stack
18console.log(stack.isEmpty());

Output

3
3
2
1
false
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.

  • .× 25
  • (× 22
  • )× 22
  • ;× 15
  • {× 7
  • }× 7
  • =× 5
  • [× 2
  • ]× 2
  • -× 1

More JavaScript examples at level 5

← JavaScript typing practice