Check for balanced brackets in JavaScript
Advanced · 4 min read
Code editors highlight a bracket in red when it has no partner. Calculators refuse (2 + 3]. Both are checking that brackets are balanced: every opening bracket is closed by the same kind, in the right order. It is one of the most common interview questions, and it is the best way to meet a stack, a tool you will use for undo buttons, browser history and parsing.
In this tutorial you will write isBalanced, see why simply counting brackets isn't enough, and learn how a stack remembers what is still open. You should know for...of loops and the array methods push and pop. The stack is explained from zero.
What balanced means
(a[b]{c})is balanced: every bracket closes in the reverse order it opened.(]is not: a round bracket is closed by a square one.(is not: it never closes.)(is not: something closes before anything opened.([)]is not, and this is the tricky one. There are two openers and two closers of matching kinds, but the pairs cross. The[must close before the(does.
A stack: last in, first out
A stack is like a pile of plates. You only add to the top and you only take from the top, so the last plate you put on is the first one you take off. A JavaScript array works as a stack with two methods: push adds to the end, and pop removes and returns the last item.
That "last in, first out" order is exactly the bracket rule: the most recently opened bracket must be the next one to close.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
59 Balanced brackets
hardDecide whether every bracket in a string is closed by the right kind, in the right order. '([)]' must be rejected.
Stuck? Three hints, smallest first
- 1. Push every opener onto a stack and match every closer against the top of it.
- 2. A closer arriving with an empty stack is already a failure.
- 3. A counter cannot do this, because it has no memory of which kind was opened.
Step 1: try counting, the natural wrong turn
The first idea most people have is a counter: add one for an opener, subtract one for a closer, and fail if it ever goes below zero.
function byCounting(text) {
let depth = 0;
for (const c of text) {
if (c === '(' || c === '[') depth++;
else if (c === ')' || c === ']') depth--;
if (depth < 0) return false;
}
return depth === 0;
}
console.log(byCounting('(a[b])')); // true
console.log(byCounting(')(')); // false
console.log(byCounting('([)]')); // true, but it is not balanced
The counter catches a closer arriving first and an opener left open. But ([)] passes. The counter only knows how many brackets are open, not which kind. It has no memory of whether the last one was round or square.
Step 2: push openers, pop for closers
const stack = [];
stack.push('(');
stack.push('[');
console.log(stack); // [ '(', '[' ]
console.log(stack.pop()); // '['
console.log(stack); // [ '(' ]
When we read an opener, we push it. When we read a closer, we pop the top item, which is the most recently opened bracket, and check it is the right kind.
Step 3: matching kinds with a lookup object
Each closer needs to know its opener. A small object answers that:
const closes = { ')': '(', ']': '[', '}': '{' };
console.log(closes[']']); // '['
console.log(')' in closes); // true
console.log('a' in closes); // false
closes[c] gives the opener a closer needs. c in closes asks "is this character a closer?". Every other character, letters included, is ignored.
Step 4: put it together
function isBalanced(text) {
const closes = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of text) {
if (c === '(' || c === '[' || c === '{') stack.push(c);
else if (c in closes) {
if (stack.pop() !== closes[c]) return false;
}
}
return stack.length === 0;
}
console.log(isBalanced('(a[b]{c})')); // true
console.log(isBalanced('([)]')); // false
console.log(isBalanced('(]')); // false
console.log(isBalanced('{[()()]}')); // true
Walk through ([)]. Push (, push [. Then ) arrives and pops [. A round closer needs (, so the function returns false straight away. The stack noticed what the counter missed.
Step 5: the edge cases fall out for free
function isBalanced(text) {
const closes = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of text) {
if (c === '(' || c === '[' || c === '{') stack.push(c);
else if (c in closes) {
if (stack.pop() !== closes[c]) return false;
}
}
return stack.length === 0;
}
console.log([].pop()); // undefined
console.log(isBalanced(')(')); // false
console.log(isBalanced('(')); // false
console.log(isBalanced('{[()()]')); // false
console.log(isBalanced('')); // true
console.log(isBalanced('no brackets here')); // true
When a closer arrives first, the stack is empty and pop() returns undefined. undefined never equals an opener, so the check fails without any extra code. An opener left at the end stays on the stack, and stack.length === 0 catches it. Text with no brackets at all never touches the stack, so it is balanced.
What it doesn't handle
Real code has brackets inside quotes and comments, like console.log(')'). This function counts that ) inside the quotes too, so it would call that line unbalanced. Handling it means also tracking whether you are inside a string, which is where real parsers start.
The full solution
The panel has isBalanced and the counting version, and prints both results for six inputs side by side. Press Run and find the line where they disagree, then read the checks underneath.
function isBalanced(text) {
const closes = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of text) {
if (c === '(' || c === '[' || c === '{') stack.push(c);
else if (c in closes) {
// pop() on an empty stack gives undefined, which never matches an opener.
if (stack.pop() !== closes[c]) return false;
}
}
return stack.length === 0;
}
// Counting only. Cheaper, and blind to the ORDER of the pairs.
function byCounting(text) {
let depth = 0;
for (const c of text) {
if (c === '(' || c === '[') depth++;
else if (c === ')' || c === ']') depth--;
if (depth < 0) return false;
}
return depth === 0;
}
for (const t of ['(a[b]{c})', '(]', '(', ')(', '([)]', '{[()()]}']) {
console.log(t.padEnd(10), 'stack:', String(isBalanced(t)).padEnd(6), 'counter:', byCounting(t));
}
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a matched set is balanced', isBalanced('(a[b]{c})'), true);
test('a mismatched pair is not', isBalanced('(]'), false);
test('an unclosed bracket is not', isBalanced('('), false);
test('a closer arriving first is not', isBalanced(')('), false);
test('an empty string is balanced', isBalanced(''), true);
test('text with no brackets is balanced', isBalanced('no brackets here'), true);
test('nesting several levels deep is fine', isBalanced('{[()()]}'), true);
test('one missing closer is caught by the empty-stack check', isBalanced('{[()()]'), false);
test('crossing pairs are NOT balanced', isBalanced('([)]'), false);
test('but a counter thinks they are, because it never checks the kind', byCounting('([)]'), true);
test('the counter does still catch a closer arriving first', byCounting(')('), false);
'([)]' is the input that separates a real answer from a counter. Both have the same number of openers and closers and both are non-negative throughout, so depth counting reports success. Only a stack remembers which bracket is waiting.
stack.pop() returning undefined on an empty stack is what makes the closer-arrives-first case fall out for free: undefined never equals an opener, so the comparison fails without a separate length check.
The obvious extension is the reason real parsers are harder: brackets inside a string literal or a comment do not count. Handling that means tracking whether you are inside quotes, which is the first step towards actually tokenising the language.
Common mistakes
- Counting instead of using a stack. A counter passes
([)]. Only a stack remembers which kind is open. - Forgetting the final length check. Without
stack.length === 0, an unclosed(would pass. - Comparing a closer with itself. The popped item is an opener, so look up the closer's opener with
closes[c]before comparing.
Try it yourself
- Add angle brackets
<and>as a fourth kind. - Return the position of the first bracket that breaks the rule instead of
false. - Skip anything between single quotes, so
"f(')')"counts as balanced.