A stack is a Last-In-First-Out (LIFO) data structure — the last element added is the first one removed, like a stack of plates. JavaScript arrays already behave like a stack if you only use push() and pop(), but wrapping that behavior in a class makes the intent explicit and prevents accidental misuse of other array methods.
JavaScript Program to Implement a Stack Using an Array
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) return "Stack is empty";
return this.items.pop();
}
peek() {
if (this.isEmpty()) return "Stack is empty";
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log("Top element:", stack.peek());
console.log("Popped:", stack.pop());
console.log("Stack size after pop:", stack.size());
Output:
Top element: 30
Popped: 30
Stack size after pop: 2
All four operations — push, pop, peek, and isEmpty — run in O(1) constant time because they only ever touch the end of the underlying array, never shift or re-index the rest of it. Stacks like this show up constantly in real code: the browser’s back-button history, the call stack behind function execution and recursion, undo/redo features, and balanced-parentheses/bracket-matching checks.
