A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle, where elements are added and removed from the same end. In JavaScript, a stack can be implemented using an array. Methods like push()
and pop()
handle insertion and removal, respectively. A custom stack implementation can include additional methods like peek()
to view the top element and isEmpty()
to check if the stack is empty. For example:
javascript
class Stack {
constructor() {
this.items = [];
}
push(element) { this.items.push(element); }
pop() { return this.items.pop(); }
peek() { return this.items[this.items.length - 1]; }
isEmpty() { return this.items.length === 0; }
}