Start learning free

LESSON 66 OF 70 · PROJECTS: OBJECT-ORIENTED

Stack in TypeScript: Build a MyStack Class on an Array

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: number[] and offers four operations.

The methods:

  • push(value: number): void
  • pop(): number
  • peek(): number
  • size(): number

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. (Calling pop() or peek() on an empty stack would return undefined at run time.)

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

const 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(), but pop() may return undefined, so write this.data.pop()! to tell TypeScript the value is there. The last element is this.data[this.data.length - 1].

class MyStack {
    private data: number[] = [];

    push(value: number): void {
        this.data.push(value);
    }

    pop(): number {
        return this.data.pop()!;
    }

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

    size(): number {
        return this.data.length;
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: OBJECT-ORIENTED

    Stack Impl in TypeScript, 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. The lesson asks for a class MyStack that stores whole numbers in a private array, data: number[], and offers four operations:

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

    The driver pushes 10, 20 and 30, then peeks, reads the size, pops three times with a size check in between, and finally pushes 7 to show that the stack keeps working after it has been emptied. The lesson's tests never pop or peek an empty stack.

    Following the output: after the three pushes the top is 30 and the size is 3. The first pop returns 30 and leaves a size of 2. The next two pops return 20 and 10, in reverse order of pushing, and the size is 0. After push(7), the top is 7 and the size is 1.

    Approach: the end of the array is the top of the stack

    An array already has what a stack needs. Its push adds at the end and its pop removes from the end, and both are fast, because nothing else has to move. If the end of the array is the top of the stack, the last value pushed is always the last element, which is exactly the LIFO rule. Putting the top at the front instead would force every element to shift on each operation.

    The class wraps the array and hides it. The field is declared private, so code outside the class can use only the four methods. That is the point of building MyStack at all: the rest of the program doesn't know whether the values live in an array, and the class could change its storage later without breaking the callers.

    Step by step

    1. Declare the class MyStack and write its closing brace at once. The driver's new MyStack() builds an object from it.
    2. Declare the field private data: number[] = [];. The initializer gives every new stack its own empty array, and private keeps it away from outside code.
    3. Start push with a number parameter named value and the return type void.
    4. Call the array's own push inside it, so the value lands at the end.
    5. Start pop, with no parameters and the return type number.
    6. Return what the array's pop removes. The lesson adds a ! after the call, a non-null assertion that tells the compiler the value is not undefined.
    7. Start peek, again returning a number.
    8. Return the last element, this.data[this.data.length - 1]. With three values the last index is 2. Reading by index removes nothing.
    9. Start size, returning a number.
    10. Return this.data.length: one array element per stored value.

    The solution in TypeScript

    class MyStack {
        private data: number[] = [];
    
        push(value: number): void {
            this.data.push(value);
        }
    
        pop(): number {
            return this.data.pop()!;
        }
    
        peek(): number {
            return this.data[this.data.length - 1];
        }
    
        size(): number {
            return this.data.length;
        }
    }
    
    const 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());
    

    It prints:

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

    TypeScript details worth knowing

    • Two different push and pop. Inside MyStack.push, this.data.push(value) calls the array's method. Both share a name but belong to different objects: this.data is an array, and this is the stack.
    • The ! operator. An array's pop is typed to return number | undefined when the compiler runs in strict mode, because an empty array gives undefined. The ! removes undefined from the type so that it fits the return type number. The lessons compile with --strict false, where the type of pop() is already number and the ! changes nothing. Under strict checking, const v: number = a.pop(); is reported as Type 'number | undefined' is not assignable to type 'number'. Either way, ! is erased when the code compiles: it checks nothing at run time.
    • private is a compile-time rule. Writing w.data outside the class makes the compiler report Property 'data' is private and only accessible within class 'MyStack'. The compiled JavaScript still runs, and after w.push(5) the expression w.data evaluates to [ 5 ]. Use #data if you need privacy at run time.
    • Indexing past the end is not an error. A JavaScript array read at a missing index gives undefined. That is why peek needs no special case to compile, and why it misbehaves quietly on an empty stack.
    • Field initializers. = [] runs once per object, so two stacks never share an array.

    Complexity

    Every operation is O(1) time: push and pop work at the end of the array, peek reads one index, and size reads the stored length. (Array push is amortized O(1): the engine occasionally grows its storage, but the average cost per call stays constant.) The stack holds one array element per value, so the space is O(n) for n values.

    Edge cases and common mistakes

    • Empty stack. The lesson's tests never pop or peek an empty stack. With this solution, on an empty stack pop() and peek() both return undefined at run time even though their declared type is number, and size() is 0. If you want an error instead, check this.data.length === 0 first and throw.
    • Using shift or index 0 as the top. The array's shift and unshift work at the front and move every element along. Keep the top at the end.
    • Peeking with pop. peek must not remove the value: after peek() the size is unchanged. After pop() it drops by one.
    • Off by one in peek. this.data[this.data.length] is one past the last element and gives undefined. The last index is length - 1.
    • Sharing one array. Declaring the array outside the class, or reusing one object, would make separate stacks see each other's values. Declare it as a field with an initializer.
    • Using the field without this.. Inside a method, data alone is not defined. It is this.data.
    • Reuse after emptying. The stack must keep working after the last pop. Because the array is just empty, push(7) afterwards makes the top 7 and the size 1.

    Testing

    • Push 1 and 2: peek() returns 2 and size() returns 2.
    • Then pop() returns 2, peek() returns 1 and size() returns 1.
    • A new stack has size() 0.
    • Push 10, 20, 30 and pop three times: the values come out as 30, 20, 10.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free