0

I am new to JS and I have a question about the return statement. Why do I have to use return false to get out a forEach loop in JS?

This here works fine:

let answer;
    let found = false;
    for (let i = 0; i < database.length; i++){
        let p = database[i];
        if (p.id === person.id){
            database[i] = person; //Overwrite if found
            answer = 'Person information changed.';
            found = true;
            break;
        }
    }

But this on the other hand doesn't work:

database.forEach(element => {
        if(element.email == req.body.email || element.nachname == req.body.nachname || element.vorname == req.body.vorname)
            res.send(element);
            break;
    });

I got this error -> SyntaxError: Illegal break statement.

Is there any difference between those loops? I know you can break a loop like for, while and switch loop but what makes forEach different?

Thank you!

Haidepzai
  • 764
  • 1
  • 9
  • 22
  • 4
    break doesn't work inside forEach, see [this](https://www.codepunker.com/blog/3-javascript-loop-gotchas) and [this](https://stackoverflow.com/questions/6260756/how-to-stop-javascript-foreach) – Ramesh Reddy Dec 13 '19 at 13:19
  • 1
    Check this https://stackoverflow.com/questions/2641347/short-circuit-array-foreach-like-calling-break – Observer Dec 13 '19 at 13:19
  • @Ramesh — The question has already observed that. It is asking why. – Quentin Dec 13 '19 at 13:20
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong too. – Shantanu Terang Dec 13 '19 at 13:23

2 Answers2

2

Reason is that we are passing a callback function to forEach function. Meaning you can't use loop conditions such as break and continue.

Adrian
  • 8,271
  • 2
  • 26
  • 43
1

Code running inside a forEach is in a different function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335