Step 2 of 5

40% Complete

Push Operation

Learn how to add elements to a stack

The Push Operation

The push operation adds an element to the top of the stack. It's one of the fundamental operations that defines a stack's behavior.

Think of it like placing a plate on top of a stack of plates. The new plate becomes the top of the stack, and it's the first one you'll remove when you need a plate.

Implementing Push

In our array-based implementation, the push operation is straightforward. We simply add the new element to the end of the array, which represents the top of our stack.

Push Implementation
class Stack {
constructor() {
this.items = [];
}
// Push: Add an element to the top of the stack
push(element) {
// Simply add the element to the end of the array
this.items.push(element);
// Optional: return this for method chaining
return this;
}
// Other methods...
}

Before Push

The stack is empty

Stack with elements: [10, 20, 30]

After Push(40)

The stack is empty

Stack with elements: [10, 20, 30, 40]

How Push Works

Let's break down the push operation step by step:

  1. Accept an element - The push method takes a parameter, which is the element to be added to the stack.
  2. Add to the top - In our array implementation, we add the element to the end of the array using the built-in push method of JavaScript arrays.
  3. Return the stack instance - Optionally, we return this (the stack instance) to allow for method chaining, which can be useful in some scenarios.

Key Points About Push:

  • Time Complexity: O(1) - The push operation is constant time, meaning it takes the same amount of time regardless of how many elements are in the stack.
  • Stack Growth: In JavaScript, arrays automatically resize, so we don't need to worry about stack overflow. In languages with fixed-size arrays, you would need to check if the stack is full before pushing.
  • Method Chaining: Returning this allows for method chaining like stack.push(10).push(20).push(30).

Push Operation in Action

Here's an example of using the push operation to build a stack:

Using Push
// Create a new stack
const stack = new Stack();
// Push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Stack now contains [10, 20, 30] with 30 at the top
// We can also chain push operations
stack.push(40).push(50);
// Stack now contains [10, 20, 30, 40, 50] with 50 at the top

The stack is empty

Final stack after all push operations

Check Your Understanding

Next Steps

Now that you understand how to add elements to a stack with the push operation, let's move on to learning how to remove elements with the pop operation.