11 points · by bhalp1 · 9y ago · 6 comments
One example: if you want to iterate over the elements of an array `a` of size `n`, the header of the `for` loop will look like this:
for (i=0; i<n; i++) {
element = a[i];
...
}
The `i=0` part is related to knowledge that the first element of an array has index zero, and the `i<n` part kind of follows from it -- if `n` is the length of the array, and `0` is the first index, then `n-1` is the last index.Compare this to
a.forEach(function (element) { ... })
Here, you don't have to know that the first index is 0 and you can't make the mistake of writing `<=` where `<` would have been correct.So the "tax" that the OP is talking about is the cognitive overhead of having to know all these things about the array representation, and making sure to get these details right.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."
— Brian W. Kernighan and P. J. Plauger in The Elements of Programming Style.
[0]: https://jsperf.com/foreach-vs-reduce-vs-for-loop
For loops have also an advantage that they can be used with yield and await (generators and async functions) while you cannot place these keywords inside a callback function.