A stack is a linear data structure that behaves like a real-world stack of items. It follows a last in, first out (LIFO) order of operations, similar to its real-world counterpart. This means that new items are added to the top of the stack and items are removed from the top of the stack as well.
The main operations of a stack data structure are:
push
: Adds an element to the top of the stackpop
: Removes an element from the top of the stackpeek
: Retrieves the element at the top of the stack, without removing itisEmpty
: Checks if the stack is emptyclass Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.unshift(item);
}
pop(item) {
return this.items.shift();
}
peek(item) {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
class
with a constructor
that initializes an empty array, items
, for each instance.push()
method, which uses Array.prototype.unshift()
to add an element to the start of the items
array.pop()
method, which uses Array.prototype.shift()
to remove an element from the start of the items
array.peek()
method, which retrieves the value of the first element in the items
array, without removing it.isEmpty()
method, which uses Array.prototype.length
to determine if the items
array is empty.const stack = new Stack();
stack.push('apples');
stack.push('oranges');
stack.push('pears');
stack.isEmpty(); // false
stack.peek(); // 'pears'
stack.pop(); // 'pears'
stack.pop(); // 'oranges'
stack.pop(); // 'apples'
stack.isEmpty(); // true
Would you like to help us improve 30 seconds of code?Take a quick survey
Snippet collection
A guide to some of the most commonly-used data structures, along with JavaScript implementations and examples.
JavaScript, Object
A queue is a linear data structure which follows a first in, first out (FIFO) order of operations.
JavaScript, Object
Sorts an array of objects, ordered by properties and orders.
JavaScript, Object
A doubly linked list is a linear data structure where each element points both to the next and the previous one.