Balanced Brackets Checker Using a Stack

Check whether parentheses, square brackets and braces are balanced and correctly nested with a single-pass stack algorithm.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
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 early throw when 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

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.