šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Break from forEach in JavaScript

Let's say we have the following data:

const names = [
    {name: 'Spiros', contry: 'šŸ‡¬šŸ‡·'},
    {name: 'Bjorn', contry: 'šŸ‡©šŸ‡°'},
    {name: 'Theo', contry: 'šŸ‡¬šŸ‡·'},
]

The problem

We want to loop through the names array and:

  • print the county flag for the name Bjorn
  • stop the loop when we found what we were searching for.

With a classical for loop, we could do this very easily by using the Javascript break keyword:

for (const n of names) {
    if (n.name === 'Bjorn') {
        console.log(n.flag)
        break;
    }
}

However, if we try to do the same with a forEach loop we will get an error:

names.forEach(n => {
    if(n.name === 'Bjorn') {
        console.log(n.flag)
        // ā›”ļø this will not work
        // Uncaught SyntaxError: Illegal break statement 
        break;
    }
})

The reason for the Uncaught SyntaxError: Illegal break statement is that the break statement works only within loops and forEach() is a function.

The solution

There are multiple ways to use forEach() and stop when we found want we are searching for.

In my opinion, the best fix for this using the Array.find() method:

const result = names.find(n => n.name === 'Bjorn')
result.flag // šŸ‡©šŸ‡°

Keep in mind that find() will end after finding the first result, exactly as a break statement will do:

// āš ļø find will return ONLY the first result
const result = names.find(n => n.flag === 'šŸ‡¬šŸ‡·')
result // {name: 'Spiros', contry: 'šŸ‡¬šŸ‡·'}

If we want to get the index of the first result we can use Array.findIndex():

const index = names.findIndex(n => n.name === 'Theo')
index // 3

You can checkout the full code on Github, and here is the live example.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *