šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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