Stack

IsEmpty Operation

What is the isEmpty Operation in Stack?

isEmpty just tells you whether there's anything on the stack at all. It exists so you can guard pop() and peek() calls: checking first avoids trying to read or remove from a stack that has nothing in it.

How Does It Work?

Consider a stack represented as an array: [ ] (empty) or [5, 3, 8] (with elements).

  1. For an empty stack [ ], isEmpty() returns true.
    size = 0emptynoneisEmpty() → true
  2. For a non-empty stack [5, 3, 8], isEmpty() returns false.
    size = 3538topisEmpty() → false
Returns true (nothing on the stack)Returns false (at least one element)

The operation simply checks if the stack's size/length is zero. Notice it never reads any of the values — only the size line and whether there is a top at all, which is why it costs the same no matter how tall the stack gets.

Algorithm Implementation

  1. Check the current size/length of the stack
  2. Return the result :
    • true if size equals 0.
    • false otherwise.

Time Complexity

  • O(1) constant time complexity.:
  • The operation only needs to check one value (size/length) regardless of stack size.:

Practical Usage

  1. Prevent stack underflow errors before pop() operations.
  2. Check if there are elements to process.
  3. Validate stack state in algorithms.
  4. Terminate processing loops when stack becomes empty.

The isEmpty operation is a simple but crucial part of stack implementation, ensuring safe stack manipulation and preventing runtime errors.

Visualize the IsEmpty operation on a stack

Stack is empty

Test Your Knowledge before moving forward!

Stack Quiz Challenge

How it works:

  • +1 point for each correct answer
  • 0 points for wrong answers
  • Earn stars based on your final score (max 5 stars)

Stack IsEmpty Implementation

// Stack Implementation with isEmpty Operation in JavaScript
class Stack {
  constructor() {
    this.items = [];
    this.top = -1;
  }

  // Push operation
  push(element) {
    this.items[++this.top] = element;
    console.log(`Pushed: ${element}`);
  }

  // Pop operation
  pop() {
    if (this.isEmpty()) {
      console.log("Stack Underflow - Cannot pop from empty stack");
      return -1;
    }
    return this.items[this.top--];
  }

  // Check if stack is empty
  isEmpty() {
    const empty = this.top === -1;
    console.log(`Stack is ${empty ? "empty" : "not empty"}`);
    return empty;
  }

  // Display stack
  display() {
    console.log("Current Stack:", this.items.slice(0, this.top + 1));
  }
}

// Usage
const stack = new Stack();
console.log("Initial stack check:");
stack.isEmpty();  // true

stack.push(10);
stack.push(20);
stack.display();
stack.isEmpty();  // false

stack.pop();
stack.pop();
stack.isEmpty();  // true

Done With the Learning

Mark Stack : isEmpty as done and view it on your dashboard

Explore other operations