{"id":1961,"date":"2022-06-08T17:49:39","date_gmt":"2022-06-08T15:49:39","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=1961"},"modified":"2022-06-08T17:49:39","modified_gmt":"2022-06-08T15:49:39","slug":"how-to-break-out-of-a-javascript-foreach-loop","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2022\/06\/08\/how-to-break-out-of-a-javascript-foreach-loop\/","title":{"rendered":"How to Break Out of a JavaScript forEach() Loop"},"content":{"rendered":"\n<p>JavaScript\u00b4s <span class=\"has-inline-color has-vivid-cyan-blue-color\">forEach() <\/span>function\u00a0executes a function on every element in an array. However, since\u00a0<code>forEach()<\/code>\u00a0is a function rather than a loop, using\u00a0<a href=\"https:\/\/www.w3schools.com\/js\/js_break.asp\">the\u00a0<code>break<\/code>\u00a0statement<\/a>\u00a0is a syntax error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;1, 2, 3, 4, 5].forEach(v => {\r\n  if (v > 3) {\r\n    \/\/ SyntaxError: Illegal break statement\r\n    break;\r\n  }\r\n});<\/code><\/pre>\n\n\n\n<p> If you find yourself stuck with a\u00a0<code>forEach()<\/code>\u00a0that needs to stop after a certain point and refactoring to use\u00a0<code>for\/of<\/code>\u00a0is not an option, here&#8217;s 3 workarounds:<\/p>\n\n\n\n<h4>1. Use\u00a0<code>every()<\/code>\u00a0instead of\u00a0<code>forEach()<\/code><\/h4>\n\n\n\n<p>The\u00a0<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/every\"><code>every()<\/code>\u00a0function<\/a>\u00a0behaves exactly like\u00a0<code>forEach()<\/code>, except it stops iterating through the array whenever the callback function returns a\u00a0<span class=\"has-inline-color has-vivid-cyan-blue-color\"> falsy value<\/span><a href=\"https:\/\/masteringjs.io\/tutorials\/fundamentals\/falsy\">.<\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Prints \"1, 2, 3\"\r\n&#91;1, 2, 3, 4, 5].every(v => {\r\n  if (v > 3) {\r\n    return false;\r\n  }\r\n\r\n  console.log(v);\r\n  \/\/ Make sure you return true. If you don't return a value, `every()` will stop.\r\n  return true;\r\n});<\/code><\/pre>\n\n\n\n<p>With\u00a0<code><em><strong>every()<\/strong><\/em><\/code>,\u00a0<code><em><span class=\"has-inline-color has-vivid-cyan-blue-color\">return false<\/span><\/em><\/code>\u00a0is equivalent to a\u00a0<code><span class=\"has-inline-color has-luminous-vivid-orange-color\">break<\/span><\/code>, and\u00a0<code><em><span class=\"has-inline-color has-vivid-cyan-blue-color\">return true<\/span><\/em><\/code>\u00a0is equivalent to a\u00a0<code><span class=\"has-inline-color has-luminous-vivid-orange-color\">continue<\/span><\/code>.<\/p>\n\n\n\n<p>Another alternative is to use the\u00a0<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/find\"><code>find()<\/code>\u00a0function<\/a>, which is similar but just flips the boolean values. With\u00a0<code><em><strong>find()<\/strong><\/em><\/code>,\u00a0<code><em><span class=\"has-inline-color has-vivid-cyan-blue-color\">return true<\/span><\/em><\/code>\u00a0is equivalent to\u00a0<code><span class=\"has-inline-color has-luminous-vivid-orange-color\">break<\/span><\/code>, and<em><span class=\"has-inline-color has-vivid-cyan-blue-color\">\u00a0<code>return false<\/code>\u00a0<\/span><\/em>is equivalent to\u00a0<code><span class=\"has-inline-color has-luminous-vivid-orange-color\">continue<\/span><\/code>.<\/p>\n\n\n\n<h4>2. Filter Out The Values You Want to Skip<\/h4>\n\n\n\n<p>Instead of thinking about how to\u00a0<code>break<\/code>\u00a0out of a\u00a0<code>forEach()<\/code>, try thinking about how to filter out all the values you don&#8217;t want\u00a0<code>forEach()<\/code>\u00a0to iterate over. This approach is more in line with functional programming principles.<\/p>\n\n\n\n<p>The\u00a0<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/findIndex\"><code>findIndex()<\/code>\u00a0function<\/a>\u00a0takes a callback and returns the first index of the array whose value the callback returns truthy for. Then the\u00a0<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/slice\"><code>slice()<\/code>\u00a0function<\/a>\u00a0copies part of the array.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Prints \"1, 2, 3\"\r\nconst arr = &#91;1, 2, 3, 4, 5];\r\n\r\n\/\/ Instead of trying to `break`, slice out the part of the array that `break`\r\n\/\/ would ignore.\r\narr.slice(0, arr.findIndex(v => v > 3)).forEach(v => {\r\n  console.log(v);\r\n});<\/code><\/pre>\n\n\n\n<h4>3. Use a\u00a0<code>shouldSkip<\/code>\u00a0Local Variable<\/h4>\n\n\n\n<p>If you can&#8217;t use\u00a0<code>every()<\/code>\u00a0or\u00a0<code>slice()<\/code>, you can check a\u00a0<em><strong><code>shouldSkip<\/code>\u00a0flag<\/strong><\/em> at the start of your\u00a0<code>forEach()<\/code>\u00a0callback. If you set\u00a0<code>shouldSkip<\/code>\u00a0to\u00a0<code>true<\/code>, the\u00a0<code>forEach()<\/code>\u00a0callback returns immediately.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Prints \"1, 2, 3\"\r\nlet shouldSkip = false;\r\n&#91;1, 2, 3, 4, 5].forEach(v => {\r\n  if (shouldSkip) {\r\n    return;\r\n  }\r\n  if (v > 3) {\r\n    shouldSkip = true;\r\n    return;\r\n  }\r\n\r\n  console.log(v);\r\n});<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>JavaScript\u00b4s forEach() function\u00a0executes a function on every element in an array. However, since\u00a0forEach()\u00a0is a function rather than a loop, using\u00a0the\u00a0break\u00a0statement\u00a0is a syntax error: If you find yourself stuck with a\u00a0forEach()\u00a0that needs to stop after a certain point and refactoring to use\u00a0for\/of\u00a0is not an option, here&#8217;s 3 workarounds: 1. Use\u00a0every()\u00a0instead of\u00a0forEach() The\u00a0every()\u00a0function\u00a0behaves exactly like\u00a0forEach(), except it [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1963,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[5],"tags":[565,563,564,561,562,115],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/1961"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=1961"}],"version-history":[{"count":1,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/1961\/revisions"}],"predecessor-version":[{"id":1964,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/1961\/revisions\/1964"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/1963"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=1961"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=1961"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=1961"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}