A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It means the last element added to the stack will be the first one to be removed.
Imagine a stack of books where you can only add or remove books from the top.
Stacks are widely used in various programming scenarios, such as function calls, undo-redo operations, and browser history management. They provide an efficient way to manage elements in a specific order.
- push(): This method adds an element to the top of the stack.
- pop(): This method removes and returns the topmost element from the stack.
Let’s see an example:
const stack = ;
console.log(stack.pop()); // Output: ‘element 3’
console.pop()); // Output: ‘element 2’
In this example, we initialize an empty array called `stack`. We then use `push()` to add elements to the stack and `pop()` to remove elements from the stack.
The elements are accessed in reverse order, just like a stack.
- length: Returns the number of elements in the stack.
- peek(): Returns the topmost element without removing it.
- isEmpty(): Checks if the stack is empty or not.
Here’s an example that demonstrates these operations:
console.length); // Output: 0
console.isEmpty()); // Output: true
console.peek()); // Output: ‘element 2’
console.length); // Output: 1
console.isEmpty()); // Output: false