Monday, January 6, 2025
HomeProgrammingImplementation of a Stack in JavaScript

Implementation of a Stack in JavaScript

A stack follows the LIFO (Last In, First Out) principle. You can implement it using an array or a class.

1. Using an Array

javascript
let stack = [];
stack.push(1); // Add element
stack.push(2);
stack.pop(); // Remove the top element

2. Using a Class

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;
}
}

Usage:

javascript
const stack = new Stack();
stack.push(10);
stack.push(20);
console.log(stack.pop()); // Outputs: 20
console.log(stack.peek()); // Outputs: 10

This approach is simple, efficient, and encapsulates stack operations.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x