Array Stack Basics in JavaScript
• javascriptarraysstackbeginnersdata structurescoding snippet
Use a JavaScript Array as a Stack
A stack follows LIFO (last in, first out). With arrays, push
adds to the top and pop
removes from the top.
Use peek
to read the top item and isEmpty
to check if the stack has elements.
// Array as Stack (LIFO)
const stack = []; // Push: O(1)
function push(x) { stack.push(x);
} // Pop: O(1)
function pop() { return stack.pop();
} // Peek: O(1)
function peek() { return stack[stack.length - 1];
} // isEmpty: O(1)
function isEmpty() { return stack.length === 0;
} // Demo
push(10);
push(20);
push(30);
console.log('Top:', peek()); // 30
console.log('Popping:', pop()); // 30
console.log('Top after pop:', peek()); // 20 // Empty the stack
while (!isEmpty()) { console.log('Popping:', pop());
}
console.log('Empty?', isEmpty()); // true
Why this matters: Stacks are used in undo systems, depth-first search (DFS), backtracking, and expression evaluation.