loops and forEach
if i have for example ,
u can at any point i can stop the loop from doing any further loops using break
but if I have something like,
is it possible to add something similar to
break
in the if condition that'll stop the forEach from doung further operation on the items from arr2??5 Replies
there is not
you can use for/of if you need to break, it's simpler than a regular for loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
you could force a break by changing the length of the arr1 once you find a match but of course that will mutate your array.
As Jochem said,
.forEach()
will iterate through all elements in the array, no breaking. The for...of
loop is what you're looking for:
The return statement will kill the for loops.
If we add a console.log
in there, we see that it does indeed stop at 3 == 3
:
Produces:
Moral of the story: the .filter()
, .map()
, .reduce()
, .forEach()
, and other array methods work on every element of the array provided, that's their job. If you want to not do a thing on every element in an array you need a for...of
loop.this doesn't work https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#description
Note, however, that the length of the array is saved before the first invocation of callbackFn
.
yaa that's what I did actually xD
but it doesn't sound very good ahaha
i feel like it might create more complexity
yaa i got it..tnx❤️