Thursday, 1 December 2016

Caution when use return with forEach

This will probably not happen to you if you are very clear with JS's this notion. However it did happen to me today and caused me several minutes to figure out what was wrong.

So, this is what happened.

Return is something you'd first think of if you want to, for example, check something in an array, and if nothing is found at all, do something else. You can see why return fits in here - if something is indeed found, it elegantly returns the result and exits the function. The idea itself is quite natural, however when it comes to JS, you might want to be more cautious, if you are iterating through the array using forEach.

Why is that?

Because return will only exit the current this context. And, if you are using forEach, which takes your iteration(your return statement includes) in a callback function, it will only exit this callback function, instead of the whole function as you might desire!

See the next fiddle for a illustration of the problem.



No comments:

Post a Comment