Balanced Brackets Checker Using a Stack
Check whether parentheses, square brackets and braces are balanced and correctly nested with a single-pass stack algorithm.
Code
const PAIRS = new Map([
[")", "("],
["]", "["],
["}", "{"],
]);
export function isBalanced(input) {
if (typeof input !== "string") throw new TypeError("input must be a string");
const stack = [];
for (const char of input) {
if ("([{".includes(char)) {
stack.push(char);
} else if (PAIRS.has(char)) {
if (stack.pop() !== PAIRS.get(char)) return false;
}
}
return stack.length === 0;
}How it works
Count the function isBalanced as the entire surface area of Balanced Brackets Checker Using a Stack.
The file repeats itself only inside for (const char of input). A guard precedes the TypeError: bad state stops the flow there instead of continuing.
Points of care
- The guard
typeof input !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
Signature: export function isBalanced(input)
isBalanced is the public entry point; everything else in the file exists to support it.
Key statements
if (typeof input !== "string") throw new TypeError("input must be a string");
if (stack.pop() !== PAIRS.get(char)) return false;
return stack.length === 0;
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What happens if the preconditions do not hold?
- `TypeError` is raised at the guard (`typeof input !== "string"`), so invalid state never reaches the main logic.
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `isBalanced` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.