This content originally appeared on David Walsh Blog and was authored by David Walsh
I’ve written a number of blog posts about JavaScript tricks: Promise tricks, type conversion tricks, spread tricks, and a host of other JavaScript tricks. I recently ran into another JavaScript trick that blew my mind: how to break a forEach
loop, shared by Andrea Giammarchi!
To break the forEach
loop at any point, you can truncate the array’s length
:
const myArray = [1, 2, 3]; myArray.forEach(item => { // ... do some stuff if(someConditionIsMet) { // Break out of the loop by truncating array myArray.length = 0; } })
By setting the array’s length
to 0
, you empty out the array and immediately halt the forEach
. Of course, emptying out the array loses its original data, so you may want to create a new array ([...myArray].forEach
) before this operation.
Another way of accomplishing the task would be throwing an exception instead:
// https://stackoverflow.com/questions/2641347/short-circuit-array-foreach-like-calling-break let BreakException = {}; try { [1, 2, 3].forEach(function(el) { console.log(el); if (el === 2) throw BreakException; }); } catch (e) { if (e !== BreakException) throw e; }
And of course, there will likely be a better way to get what you want without needing this trick, like using .find
or .some
, but not every trick needs to be a best practice!
The post Break a forEach Loop with JavaScript appeared first on David Walsh Blog.
This content originally appeared on David Walsh Blog and was authored by David Walsh
David Walsh | Sciencx (2020-12-22T12:00:53+00:00) Break a forEach Loop with JavaScript. Retrieved from https://www.scien.cx/2020/12/22/break-a-foreach-loop-with-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.