Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Stack implementation using TypeScript


    A stack is an abstract data type that stores a collection of elements, with two principal operations:

    • push: adds an element to the collection
    • pop: removes the most recently added element that was not yet removed.

    The order in which elements are poped is Last In First Out aka. LIFO. In this lesson we discuss how to implement it using JavaScript / TypeScript.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    A stack is a last-in/first-out data structure with key operations having a time complexity of O(1). We can model this easily in TypeScript using the generic class for items of type T.

    The stack data structure has two key operations. The first one is push, which adds an item in O(1). The other key operation pops an item from the stack, again in O(1). If there are no more items, we can return an out-of-bound value, for example, undefined. This fact can be modeled into the type system by using a union of T and undefined.

    The objective is to implement these push and pop operations such that they operate in O(1) time. Fortunately, in JavaScript implementations, array functions that do not require any changes to the index of the current items have an average runtime of O(1).

    Therefore, we can simply implement the operations of this data structure using an array. On push, we simply push the new item into the array. As it doesn't change the index of the current items, this is O(1). Similarly, on pop, we simply pop the last value from the array. Again, it doesn't change the index of the other items in the array, so it is O(1).

    A common additional operation for collection data structures is the size, as it allows you to safely iterate the elements and find out if there are any more elements present in the data structure. Fortunately, JavaScript arrays implement this for us in the form of the length property.