Model a last-in-first-out stack
Quick answer
A stack processes the most recently added item first (LIFO). It is useful for undo histories, matching delimiters and managing pending work.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const undo=[];undo.push("insert");undo.push("rename");console.log(undo[undo.length-1],undo.pop(),undo.pop(),undo.length);Expected console output:
rename rename insert 0Peek does not remove; pop takes newest first.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function balanced(s){ const stack=[],open={")":"(","]":"["}; for(const c of s){ if(c==="("||c==="[")stack.push(c); else if(stack.pop()!==open[c])return false; } return stack.length===0;}console.log(balanced("([])"),balanced("([)]"),balanced(""));Expected console output:
true false trueThe top must match the current closing symbol.
How it works and cost model
Use push to append and pop to remove the top of an ordinary dense array; peek reads the last index without removing it. Define underflow explicitly: an empty pop returns undefined, which is ambiguous if stored values may themselves be undefined. For delimiter matching, push opening characters and pop to check each closing character, then require an empty stack. Under a dynamic-array cost model with amortized constant append and constant removal at the end, a scan is O(n) time and at most O(n) stack storage. These are model-based bounds, not ECMAScript complexity promises.
Common mistakes
Do not use a queue when matching nested delimiters. Check both unexpected closing symbols and unmatched opening symbols at the end.
Practice
Use a stack to validate strings containing only parentheses and brackets. Compare "([])" and "([)]" and the empty string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Model a last-in-first-out stack — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
Which element is removed first from a LIFO undo stack?
Why check stack length after processing balanced delimiters?
What distinguishes peek from pop on a nonempty stack?
What is the exact console output in the LIFO stack example 1?
const undo=[];undo.push("insert");undo.push("rename");console.log(undo[undo.length-1],undo.pop(),undo.pop(),undo.length);What is the exact console output in the LIFO stack example 2?
function balanced(s){ const stack=[],open={")":"(","]":"["}; for(const c of s){ if(c==="("||c==="[")stack.push(c); else if(stack.pop()!==open[c])return false; } return stack.length===0;}console.log(balanced("([])"),balanced("([)]"),balanced(""));