Summary: This tutorial introduces you to the JavaScript stack data structure and shows you how to use an array as a stack.
Introduction to the stack data structure
A stack is a data structure that holds a list of elements. It operates based on the LIFO principle (Last In, First Out), meaning the most recently added element is the first to be removed.
A stack has two main operations that happen only at the top: push and pop.
The push operation adds an element to the top of the stack, while the pop operation removes an element from the top.
The name stack comes from the analogy to a set of physical items like DVD discs or books, stacked on top of each other.
A stack has many applications. For example, to reverse a word, you push each letter of the word into the stack and then pop the letters out.
The other applications of the stack include the “undo” mechanism in text editors, syntax parsing, function call, and expression conversion (infix to postfix, infix to prefix, postfix to infix, and prefix to infix).
JavaScript Array provides the push()
and pop()
methods, allowing you to use an array as a stack.
push() method
The push()
method adds one or more elements to the end of the array. The push()
method returns the value of the length
property that specifies the number of elements in the array.
If you consider an array as a stack, the push()
method adds one or more elements at the top of the stack.
The following example creates an empty array named stack
and adds five numbers, one by one, at the end of the stack
array. It is like to push each number into the top of the stack.
let stack = [];
stack.push(1);
console.log(stack); // [1]
stack.push(2);
console.log(stack); // [1,2]
stack.push(3);
console.log(stack); // [1,2,3]
stack.push(4);
console.log(stack); // [1,2,3,4]
stack.push(5);
console.log(stack); // [1,2,3,4,5]
Code language: JavaScript (javascript)
The following figure illustrates each step in the script above.
Initially, the stack is empty. After 5 calls to the push()
method, the stack has 5 elements.
Note that the push()
method also allows you to add multiple items to the end of the array at a time.
pop() method
The pop()
method removes the element at the end of the array and returns the element to the caller. If the array is empty, the pop()
method returns undefined.
The following example shows how to pop elements from the top of the stack using the pop()
method.
console.log(stack.pop()); // 5
console.log(stack); // [1,2,3,4];
console.log(stack.pop()); // 4
console.log(stack); // [1,2,3];
console.log(stack.pop()); // 3
console.log(stack); // [1,2];
console.log(stack.pop()); // 2
console.log(stack); // [1];
console.log(stack.pop()); // 1
console.log(stack); // []; -> empty
console.log(stack.pop()); // undefined
Code language: JavaScript (javascript)
The figure below illustrates each step in the script.
Initially, the stack has 5 elements. The pop()
method removes the element at the end of the array i.e., at the top of the stack one at a time. After five operations, the stack is empty.
Reverse a string using a JavaScript stack
The following example shows you how to reverse a string using a stack.
function reverse(str) {
let stack = [];
// push letter into stack
for (let i = 0; i < str.length; i++) {
stack.push(str[i]);
}
// pop letter from the stack
let reverseStr = '';
while (stack.length > 0) {
reverseStr += stack.pop();
}
return reverseStr;
}
console.log(reverse('JavaScript Stack')); //kcatS tpircSavaJ
Code language: JavaScript (javascript)
How the script works.
The reverse()
function accepts a string argument and returns its reversed version with the following logic:
- First, loop through the
str
and push each letter into thestack
array. - Second, pop each letter from the stack and construct the reversed string.
Note that you can use the Array.from()
method to convert a string to an array, reverse()
to reverse an array, and join()
to concatenate characters into a string:
const s = 'JavaScript Stack';
let r = Array.from(s).reverse().join('');
console.log({ r });
Code language: JavaScript (javascript)
Output:
{ r: 'kcatS tpircSavaJ' }
Code language: CSS (css)
Summary
- Use an array as a JavaScript stack data structure.
- Use the
push()
method to push an element onto the stack. - Use the
pop()
method to pop an element out of the stack.