Hacker News new | ask | show | jobs
by rwbcxrz 2517 days ago
Which foreach are you talking about? Array.prototype.forEach, for...in loops, for...of loops?

The first only works with arrays and array-like objects.

The second works on objects and arrays, but it iterates over all enumerable properties, so you don't want really want to use it for arrays. It's also made a lot less useful because it only iterates over properties, not keys.

The third finally provides some sanity, but it's only been around since ES6. Before that, lodash's each method was the most reliable way to iterate over a collection, be it an object or an array.

Just because you don't know the reason for something doesn't mean there isn't one.

2 comments

`for ... of` only iterate over objects that implement `Symbol.iterator`. Native objects don’t do that by default, so `_.forEach` is more useful the `for ... of` even if you are only targeting modern browsers and not compiling the code down to an earlier version of the spec.

That said, you can use `Object.keys`, `Object.values`, or `Object.entries` if you want to iterate over objects that don’t implement `Symbol.iterator`, so if you only need `_.forEach` there is no reason to pull in any libraries.

    Object.entries(object).forEach(([key, value]) => {
      // ...
    });
> Array.prototype.forEach

Yes, this one. If the object is an Array. According to whatever test they are using for that.

Lodash includes a reimplementation of Array.prototype.forEach because mistakes were made. It also works on other objects because other mistakes were made.

We all make mistakes. But just because there is a reason for something does not mean there is a good reason.