I’m looking through the MDN guidelines and it shows that to iterate over what seems like a defined array of data (ie. const names = ['adam', 'billy', 'cody']
) they state that we should use for of
over forEach
.
ie
// Good
for (const name of names) {
console.log(name);
}
// Less good
names.forEach(name => console.log(name));
// Definitely don't do this
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
I completely understand the last point about the for(; ;)
usage, but why not use forEach
? It’s been my usual go-to method for this type of thing for as long as I can remember.
The example given on the documentation does show it being used in a longer way such as
names.forEach(name => {
console.log('name')
});
rather than doing a quick return as I did previously name => console.log(name)
which would be more concise.
I’m just wondering what the benefit of using for of
here is, other than maybe being “explicit” about what the names belong to?