Ad space (banner)
🟨JavaScript Lessons
Lesson 64 / 69

Checking That Brackets Match (an Application of Stacks)

In this lesson you'll learn an algorithm for checking that brackets match by applying a stack, so you can understand a practical use of a data structure. This is for people searching "JavaScript check matching brackets."

Using a stack (last in, first out), you can check bracket matching by piling up opening brackets like ( or [, and checking whether each closing bracket that arrives matches the one on top whenever it appears. The procedure repeats: push when an opening bracket arrives, and when a closing bracket arrives, check whether it matches the top element and then remove it.

The sample code uses an array called stack as the stack, using .push() for opening brackets, and checking whether the value popped with .pop() for a closing bracket forms the correct pair using an object called pairs. If, at the end, stack.length === 0, you can conclude that every bracket matched correctly.

A common beginner stumbling block is judging what happens when the kinds of matching brackets don't line up (a mismatched closing bracket type). Simply counting that the number of opening and closing brackets matches isn't enough — you also need to confirm that each pair is of the correct kind, and that's the key point of this algorithm.

This is a practical example of using a stack data structure that's also applied to things like syntax checking of program code, or validating a mathematical expression. Similar ideas are used behind the scenes of an editor's autocomplete and syntax checking too.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)