Code Snippets
/

Stack via Array

Stack via Array

JavaScript does not ship a dedicated `Stack` class because `Array` already supports O(1) `push` and `pop`. This snippet covers the array-as-stack idiom, a tiny class wrapper for self-documenting code, and a balanced-parentheses checker that demonstrates the canonical stack-driven algorithm. Use this template anywhere the LIFO order matters: undo, expression evaluation, DFS bookkeeping.

JavaScript
Easy
3 snippets
data-structures
stack
code-template
arrays

402 views

8

const stack = [];
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.length);            // 3
console.log(stack[stack.length - 1]); // 3 (peek)
console.log(stack.pop());             // 3
console.log(stack);                   // [1, 2]

Array.prototype.push and Array.prototype.pop operate on the end of the array, both in O(1) amortized time. Reading the last element via array[array.length - 1] (or array.at(-1)) gives a non-mutating peek. This pattern is what most JavaScript code uses in place of a dedicated stack class. The trade-off versus a real Stack is that the array exposes other methods (shift, splice, indexed access) which a strict consumer might mis-use; if discipline matters, wrap it in a class.