Start learning free

LESSON 65 OF 68 · PROJECTS: OBJECT-ORIENTED

Stack Implementation in JavaScript: a MyStack Class

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private array field #data and offers four operations.

The methods:

  • push(value)
  • pop()
  • peek()
  • size()

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In JavaScript, pop() on an empty stack returns undefined and peek() would too.)

You start with: The starter already contains the code that uses your stack (below).

let s = new MyStack();
s.push(10);
s.push(20);
s.push(30);
console.log("Top: " + s.peek());
console.log("Size: " + s.size());
console.log("Pop: " + s.pop());
console.log("Size: " + s.size());
console.log("Pop: " + s.pop());
console.log("Pop: " + s.pop());
console.log("Empty size: " + s.size());
s.push(7);
console.log("Top: " + s.peek());
console.log("Size: " + s.size());

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

Arrays have push and pop(); the last element is this.#data[this.#data.length - 1]. The # prefix makes the field private to the class.

class MyStack {
    #data = [];

    push(value) {
        this.#data.push(value);
    }

    pop() {
        return this.#data.pop();
    }

    peek() {
        return this.#data[this.#data.length - 1];
    }

    size() {
        return this.#data.length;
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: OBJECT-ORIENTED

    Stack Impl in JavaScript, explained

    Problem overview

    A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO (last in, first out), like a pile of plates. This lesson builds a class MyStack that holds whole numbers in a private array field named #data, with four operations:

    • push(value) puts a value on top and returns nothing.
    • pop() removes the top value and returns it.
    • peek() returns the top value and leaves it on the stack.
    • size() returns how many values the stack holds.

    The lesson's tests never call pop or peek on an empty stack, and the stack must keep working after it becomes empty. The driver pushes 10, 20 and 30, then peeks, pops and pushes again. It prints:

    Top: 30
    Size: 3
    Pop: 30
    Size: 2
    Pop: 20
    Pop: 10
    Empty size: 0
    Top: 7
    Size: 1
    

    After the three pushes the top is 30 and the size is 3. The first pop returns 30. The next two return 20 and then 10, which is the reverse of the order they went in. The stack is then empty, and after pushing 7 the top is 7.

    Approach: the end of an array is the top

    A JavaScript array already behaves like a stack at its end. Adding to the end and removing from the end are both cheap, and the value added last is always the last element. So the design is to keep the values in an array and treat its end as the top of the stack.

    Putting the top at the front would work but would be a worse choice: inserting or removing at index 0 means shifting every other element. Using the end avoids that.

    The array lives in a private field. Code outside the class can use only the four methods, so nobody can reorder the values or reach into the middle of the stack. That is the point of building a stack as its own class instead of passing a bare array around.

    Step by step

    1. Declare the class MyStack. The driver's new MyStack() builds an object from it.
    2. Declare the private field #data and start it as an empty array. The initial value is written right in the field declaration, so every new stack starts empty and has its own array.
    3. Write push. It takes value and calls the array's own push on this.#data. Methods in a class have no function keyword.
    4. Write pop. It returns what the array's pop removes from its end. That one call both removes the last item and hands it back.
    5. Write peek. It returns the last item by index: this.#data.length - 1. With three values the last index is 2. Reading by index removes nothing.
    6. Write size. It returns the array's length, since there is one array item per value.

    The solution in JavaScript

    class MyStack {
        #data = [];
    
        push(value) {
            this.#data.push(value);
        }
    
        pop() {
            return this.#data.pop();
        }
    
        peek() {
            return this.#data[this.#data.length - 1];
        }
    
        size() {
            return this.#data.length;
        }
    }
    
    let s = new MyStack();
    s.push(10);
    s.push(20);
    s.push(30);
    console.log("Top: " + s.peek());
    console.log("Size: " + s.size());
    console.log("Pop: " + s.pop());
    console.log("Size: " + s.size());
    console.log("Pop: " + s.pop());
    console.log("Pop: " + s.pop());
    console.log("Empty size: " + s.size());
    s.push(7);
    console.log("Top: " + s.peek());
    console.log("Size: " + s.size());
    

    A few JavaScript details are worth a closer look:

    • Two different push methods. MyStack.push is yours. Inside it, this.#data.push(value) calls the array's built-in method. They don't clash, because they belong to different objects.
    • Private fields. #data is visible only inside the class body. Outside, s.data is just an unrelated property that reads undefined, and writing s.#data is a syntax error.
    • A field initialiser runs for each object. #data = []; creates a new array every time new MyStack() runs. Two stacks never share their values: pushing onto one leaves the other's size unchanged.
    • size is a method. Call it as s.size(). Writing s.size gives the function itself, not a number.
    • Indexing past the ends gives undefined. Reading an array at an index that doesn't exist doesn't throw, and a negative index like -1 is not "the last item" either: arr[-1] is undefined. That is why peek computes length - 1.

    Complexity

    Time: O(1) per operation in the usual case. Each method touches only the end of the array or reads its length. An occasional push may need the engine to grow the array's storage, but that cost averages out over many pushes.

    Space: O(n) for n values, the array that holds them. The methods add only a constant amount on top.

    Edge cases and common mistakes

    • Using shift or unshift. They work on the front of the array and shift every other element. The values would then come out in the wrong order unless every method used the same end.
    • Making peek remove the value. peek must leave the size unchanged. Calling pop inside it would shrink the stack.
    • Forgetting return in pop. The value would still be removed, but the caller would get undefined and the driver would print Pop: undefined.
    • Empty stack. The tests never do this, but in this implementation pop() and peek() on an empty stack both return undefined without throwing, and size() returns 0.
    • Reusing a stack after it empties. Nothing special is needed: after the last pop the array is empty, and pushing 7 works as on a new stack.
    • Dropping the #. A plain field data would let outside code change the stack in ways its methods don't allow.

    Testing

    • A new stack: size() returns 0.
    • Push 1, then push 2: peek() returns 2 twice in a row, and size() stays 2.
    • Push 10, 20, 30 and pop once: the result is 30 and the size is 2.
    • Push 5 on one stack while another is empty: the first has size 1 and the second still has size 0.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free