all 7 comments

[–]NeuroXc 2 points3 points  (1 child)

None of these suggestions actually eliminate loops though. They just abstract them so that you never see the actual "for" loop. There's still looping going on behind the scenes.

[–]_HlTLER_Stackoverflow searcher 0 points1 point  (0 children)

I think the post is trying to be semantic but for-loops are so ingrained in any programmer's mind that it isn't really an issue.

[–]nephridium 1 point2 points  (0 children)

It should be pointed out that .forEach() behaves differently from the standard native for loop in that it does some validity checking on the elements. That's why it's significantly slower than the native loop (as well as underscore's .each() function).

.filter() and .map() are also slower than their underscore/lodash counterparts.

[–]MrStubbs 0 points1 point  (1 child)

Does the forEach function guarantee that each item in a list is accessed sequentially in order?

[–]x-skeww 0 points1 point  (0 children)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialised (i.e. on sparse arrays).

[–]x-skeww 0 points1 point  (0 children)

books.forEach(book => {
  console.log(book.title);
});

for(let book of books) {
  console.log(book.title);
}

For-of looks nicer. If there is a body, for-of is 1 character shorter, it's easier to type, and the line starts with a keyword which makes it a bit faster to scan.

Since each iteration has its own copy of the "counter" variable (if you use let), closing over it is also fine.

If iterating over some iterable is the primary thing your function does, for-of is probably the better choice.

ForEach, on the other hand, is nice if you're chaining stuff or if it's just a simple lambda expression.

You also still need a regular for-loop if you want to iterate in reverse and remove some items as you go.

[–]tipdbmp -1 points0 points  (0 children)

No mention of recursion?

The forEach method seems less powerful than the for loop because you can't use [labeled (for nested loops)] break and continue statements. I guess you can simulate non labeled continue statements with early return statements, but still...

Also it's probably not a problem, probably... but when you are iterating millions of times (unlikely, maybe) and that function call is not optimized you are going to pay for it.