3 Things You Should Know About JavaScript's ForEach Loop
5 YEARS! This is how long I’ve been coding in JavaScript. You would think I’m an expert with loops, right? Well, apparently not. In this brief post, I’ll discuss three key things that I discovered about JavaScript’s forEach loop.
- It always returns undefined
- You can’t skip an iteration with the continue keyword
- You can’t end a loop early with the break keyword
Now, let me tell you about how I even came across these three roadblocks during my journey through the forEach loop.
A friend and I were working through a Leetcode question (Two Sum) together and I was attempting to return a value from the forEach loop. Nothing too complicated, right? I ran my code MULTIPLE times, yet no value was ever returned. How could this be possible?!
At this point, I begin to question if I was even worthy of coding. Once I made it past my shame and realized I wasn’t making much progress, I decided to do some digging into the forEach loop and here’s what I found.
1. It Always Returns Undefined
If you’re like me, you might have found this out the hard way. When trying to return a value from the forEach loop, you won’t spot the value you’re looking for. No matter what, it ONLY returns undefined.
2. You Can’t Skip an Iteration with ‘Continue’
The continue statement is used to skip over the current iteration and ‘continue’ on to the next iteration within the loop. Unfortunately, this is not allowed with the forEach loop.
Instead, you could use the return statement. Although it won’t return a value besides undefined, it will allow you to skip over the current iteration.
3. You Can’t End A Loop Early with ‘Break’
This was an issue I ran into numerous times and I could not figure out what I was doing wrong. The break statement will throw an error when using it inside of the forEach loop. Alternatively, a traditional for loop could be used and break works perfectly fine.
That’s all folks!
I hope that this post was informative. Stay tuned for more articles on JavaScript. Thanks for reading!
I enjoy talking about investing, personal finance & JavaScript. If you’re interested in chatting about anything of things, let’s connect on Twitter: @dariusthedev