Bird
Raised Fist0
DSA Javascriptprogramming

Stack Concept and LIFO Principle in DSA Javascript

Choose your learning style10 modes available
Mental Model
A stack is a collection where the last item added is the first one taken out. It works like a pile where you add and remove items only from the top.
Analogy: Imagine a stack of plates in a cafeteria. You put new plates on top and take plates from the top only. You cannot take a plate from the middle or bottom without removing the ones above it first.
Top -> [ 3 ]
        [ 2 ]
        [ 1 ]
        null
Dry Run Walkthrough
Input: Start with empty stack, push 1, push 2, push 3, then pop once
Goal: Show how items are added and removed following last-in-first-out order
Step 1: push 1 onto empty stack
Top -> [ 1 ]
        null
Why: We add the first item at the top of the stack
Step 2: push 2 onto stack
Top -> [ 2 ]
        [ 1 ]
        null
Why: New item goes on top, above the previous one
Step 3: push 3 onto stack
Top -> [ 3 ]
        [ 2 ]
        [ 1 ]
        null
Why: Keep adding items on top, last added is on top
Step 4: pop top item (3) from stack
Top -> [ 2 ]
        [ 1 ]
        null
Why: Remove the last added item first, following LIFO
Result:
Top -> [ 2 ]
        [ 1 ]
        null
Annotated Code
DSA Javascript
class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    // Add element to the top of the stack
    this.items.push(element);
  }

  pop() {
    // Remove and return the top element
    if (this.isEmpty()) {
      return null;
    }
    return this.items.pop();
  }

  isEmpty() {
    // Check if stack is empty
    return this.items.length === 0;
  }

  printStack() {
    // Print stack from top to bottom
    let result = '';
    for (let i = this.items.length - 1; i >= 0; i--) {
      result += `[ ${this.items[i]} ]\n`;
    }
    result += 'null';
    console.log('Top -> ' + result);
  }
}

// Driver code
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.printStack();
stack.pop();
stack.printStack();
this.items.push(element);
add new element on top of stack
if (this.isEmpty()) { return null; }
check if stack is empty before popping
return this.items.pop();
remove and return the top element
for (let i = this.items.length - 1; i >= 0; i--) {
iterate from top to bottom to print stack
OutputSuccess
Top -> [ 3 ] [ 2 ] [ 1 ] null Top -> [ 2 ] [ 1 ] null
Complexity Analysis
Time: O(1) for push and pop because we add or remove only the top element without traversing the stack
Space: O(n) because we store n elements in the stack array
vs Alternative: Compared to a queue where removal happens from the front, stack operations are simpler and faster for last-in-first-out access
Edge Cases
pop from empty stack
returns null safely without error
DSA Javascript
if (this.isEmpty()) { return null; }
When to Use This Pattern
When you see a problem requiring last item added to be processed first, reach for the stack pattern because it naturally follows last-in-first-out order.
Common Mistakes
Mistake: Trying to remove items from the bottom or middle of the stack
Fix: Always remove only from the top to maintain LIFO principle
Mistake: Not checking if stack is empty before popping
Fix: Add a check to avoid errors when popping from empty stack
Summary
Stack stores items so the last added is the first removed (LIFO).
Use stack when you need to reverse order or track recent items first.
Remember: push adds on top, pop removes from top, like a stack of plates.

Practice

(1/5)
1. What does the LIFO principle mean in the context of a stack?
easy
A. Elements are removed based on their value
B. First In, First Out - the first element added is the first to be removed
C. Elements are removed randomly
D. Last In, First Out - the last element added is the first to be removed

Solution

  1. Step 1: Understand the LIFO principle

    LIFO means the last element you put in is the first one you take out.
  2. Step 2: Apply to stack behavior

    Stacks follow LIFO, so the newest item is removed first.
  3. Final Answer:

    Last In, First Out - the last element added is the first to be removed -> Option D
  4. Quick Check:

    LIFO = Last In, First Out [OK]
Hint: Remember stack like a stack of plates, last added removed first [OK]
Common Mistakes:
  • Confusing LIFO with FIFO
  • Thinking elements are removed randomly
  • Assuming removal depends on element value
2. Which of the following is the correct way to push an element '5' onto a stack named stack in JavaScript?
easy
A. stack.insert(5);
B. stack.add(5);
C. stack.push(5);
D. stack.enqueue(5);

Solution

  1. Step 1: Recall JavaScript stack operations

    JavaScript arrays use push() to add elements at the end (top of stack).
  2. Step 2: Match method to stack push

    push() adds element to stack top, so stack.push(5); is correct.
  3. Final Answer:

    stack.push(5); -> Option C
  4. Quick Check:

    Push method adds element to stack [OK]
Hint: Use push() to add elements to stack in JavaScript [OK]
Common Mistakes:
  • Using add() or insert() which are not array methods
  • Confusing enqueue() with queue operation
  • Trying to use non-existent methods
3. What will be the output of the following JavaScript code?
const stack = [];
stack.push(10);
stack.push(20);
const popped = stack.pop();
console.log(popped);
console.log(stack);
medium
A. 20 [10]
B. 10 [20]
C. 10 [10, 20]
D. 20 [20]

Solution

  1. Step 1: Trace push operations

    stack.push(10) adds 10, stack.push(20) adds 20. Stack is now [10, 20].
  2. Step 2: Trace pop operation

    stack.pop() removes last element 20 and returns it. Stack becomes [10].
  3. Final Answer:

    20 [10] -> Option A
  4. Quick Check:

    Pop returns last pushed element 20 [OK]
Hint: Pop returns last pushed element, stack shrinks by one [OK]
Common Mistakes:
  • Thinking pop returns first element
  • Confusing push and pop order
  • Expecting stack unchanged after pop
4. Identify the error in the following code snippet that tries to implement a stack using an array:
const stack = [];
stack.push(1);
stack.push(2);
const top = stack.pop;
console.log(top);
medium
A. pop is used without parentheses, so it returns the function, not the popped value
B. push method is incorrect, should be pushElement
C. stack should be initialized as an object, not an array
D. console.log cannot print stack elements

Solution

  1. Step 1: Check pop usage

    stack.pop is a function reference; missing () means no call, so top is function, not value.
  2. Step 2: Understand effect on output

    console.log(top) prints function code, not popped element. Correct usage is stack.pop().
  3. Final Answer:

    pop is used without parentheses, so it returns the function, not the popped value -> Option A
  4. Quick Check:

    Call pop() with () to get value [OK]
Hint: Always use parentheses to call pop() method [OK]
Common Mistakes:
  • Forgetting parentheses on pop()
  • Thinking push method is wrong
  • Confusing array with object for stack
5. You have a stack initially empty. You perform these operations in order:
push(1), push(2), pop(), push(3), pop(), pop()

What is the final output of each pop operation in sequence?
hard
A. [2, 3, 3]
B. [2, 3, 1]
C. [2, 3, undefined]
D. [1, 3, 2]

Solution

  1. Step 1: Perform push(1) and push(2)

    Stack becomes [1, 2].
  2. Step 2: pop() removes last pushed element

    pop() returns 2, stack is now [1].
  3. Step 3: push(3)

    Stack becomes [1, 3].
  4. Step 4: pop() returns 3, stack is [1]

  5. Step 5: pop() returns 1, stack is empty

  6. Final Answer:

    [2, 3, 1] -> Option B
  7. Quick Check:

    Pop returns last pushed elements in reverse order [OK]
Hint: Track stack after each operation to find pop outputs [OK]
Common Mistakes:
  • Mixing order of popped elements
  • Assuming pop returns undefined when stack not empty
  • Confusing push and pop effects
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard