JavaScript Data Structures: What Is A Stack + Example Code
By: Jeff Lewis
2 min readNov 12, 2019
Github:
- Repository: data-structures-review
- File: stack.js
1. What Is A Stack?
A. Stack Definition:
A Stack is Linear Data Structure where data elements are arranged sequentially in an array.
Stacks and Queues are similar, but Stacks use the process of LIFO (Last In, First Out). To achieve this, the push and pop Javascript methods are used to create a Stack class in Javascript.
B. Time Complexity:
- Access: O(n)
- Search: O(n)
- Insert: O(1)
- Delete: O(1)
C. Space Complexity:
- O(n)
2. Stack Example Code
The code provided below shows 2 versions:
- With Comments:
// Stack
class Stack {
constructor () {
this.storage = [];
}; // Add Element
addElement(element) {
this.storage.push(element);
}; // Remove Element
removeElement() {
// Check If Stack Is Not Empty
if (!this.isEmpty()) {
// Remove Last Element
this.storage.pop();
}
else {
console.log('Stack is empty');
}
}; // View Last Element At Top Of The Stack
viewLastElement() {
// Check If Stack Is Not Empty
if (!this.isEmpty()) {
return this.storage[this.storage.length - 1];
}
else {
console.log('Stack is empty');
}
}; // Is Empty
isEmpty() {
// Check If Array Is Empty
if (this.storage.length === 0) {
return true;
}
else {
return false;
}
}; // View Stack
viewStack() {
return this.storage;
};
};
2. Without Comments:
class Stack {
constructor () {
this.storage = [];
}; addElement(element) {
this.storage.push(element);
}; removeElement() {
if (!this.isEmpty()) {
this.storage.pop();
}
else {
console.log('Stack is empty');
}
}; viewLastElement() {
// Check If Stack Is Not Empty
if (!this.isEmpty()) {
return this.storage[this.storage.length - 1];
}
else {
console.log('Stack is empty');
}
}; isEmpty() {
// Check If Array Is Empty
if (this.storage.length === 0) {
return true;
}
else {
return false;
}
}; viewStack() {
return this.storage;
};
};