Stack

Peek Operation

Peek Operation

Peek gives you a look at whatever's currently on top of the stack, but it leaves the stack exactly as it was: nothing gets popped.

How Does It Work?

A stack only ever exposes its top. Peek reads the value sitting there and hands it back, but unlike pop it never moves the top pointer, so the stack that comes out is the same stack that went in.

Example: Peeking at a stack

  1. Current stack, 7 on top
    537topsize 3
  2. Peek → returns 7, and the stack is left exactly as it was
    537topreturns 7size stays 3
  3. Pop → returns 7 and removes it, so 3 becomes the new top
    53topsize 2
  4. Peek → returns 3, again without removing anything
    53topreturns 3size stays 2
Read by peek (stays on the stack)Removed by popUntouched

Notice the size line under each diagram: it only changes on the pop step. That is the whole difference between the two operations — both return the top value, but only pop takes it off.

  • Time Complexity: O(1)
  • Space Complexity: O(1)

The peek operation is useful when you need to inspect the top element before deciding whether to pop it or push another element onto the stack.

Visualize the Peek 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 Peek Implementation

// Stack Implementation with Peek 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");
      return -1;
    }
    return this.items[this.top--];
  }

  // Peek operation
  peek() {
    if (this.isEmpty()) {
      console.log("Stack is empty");
      return -1;
    }
    console.log(`Top element: ${this.items[this.top]}`);
    return this.items[this.top];
  }

  // Check if stack is empty
  isEmpty() {
    return this.top === -1;
  }

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

// Usage
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.display();
stack.peek();
stack.pop();
stack.peek();

Done With the Learning

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

Explore other operations