How to break out of Array.forEach() in JavaScript, like break in a regular loop?
Hello everyone! I'm new to JavaScript and I've run into this problem.\n\nI have an array of numbers. I want to iterate through it using `forEach` and, when I find the desired value, stop further iteration. In a regular `for` loop, I would just use `break`, but in `forEach` this doesn't work — it throws an "Illegal break statement" error.\n\nHere's an example of my code:\n\n```javascript\nconst numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\nnumbers.forEach(function(num) {\n console.log('Checking number:', num);\n if (num === 5) {\n console.log('Found 5! That's enough.');\n break; // Error here!\n }\n});\n```\n\nI expected the loop to stop after the number 5, but it continues to output 6, 7, 8, 9, 10. How do I properly "break" inside `forEach`? Is there some other array method?\n\nThanks in advance.
No answers yet.
Log in to leave an answer