1

I line to write in the best practice. since I knew that for-in is a bad practice because of it's bad behavior I stopped using it. but what about using for-of ?? and which word should we use before the iterator (var, let, const) and why?


    for (const iterator of cells) {
        iterator.addEventListener('click', function (event) {
        console.log(iterator);
        });
    }

  • 1) for-in and for-of have different uses. The former is for iterating over enumerable keys of an object. The latter is for iterating over an iterator/iterable object (array, generator, array key iterators, etc.) – Andrew Li Jan 07 '18 at 07:55

1 Answers1

1

for-of is specifically for looping through the values of an iterable object, such as an array. So yes, absolutely, using for-of on an array is perfectly good practice.

and which word should we use before the iterator (var, let, const) and why

It's up to you. (But it's not an "iterator." It's a "variable" or "binding" or, loosely, "identifier". The iterator is the object used under the covers by for-of.) I use const if I don't plan to change that binding's value in the loop (and it's usually best not to), since it is a constant for each loop iteration. let is also a reasonable choice, and in both cases, any closures created within the loop won't run afoul of the closures in loops problem with that binding. But for that same reason, both let and const can have a performance implication if declared within the loop construct, because a new binding is created for each loop iteration. If you used var, it would have function scope, and thus not be recreated for each loop iteration. (But I wouldn't use var; if I have a particularly performance-sensitive bit of code where I need to avoid that binding recreation, I use let above the loop instead.)


...since I knew that for-in is a bad practice because of it's bad behavior...

for-in is not "bad behavior" if used for its purpose: Looping through the names of the enumerable properties of an object. It's just people frequently use it for looping through the indexes of an array, which it's not designed for and not the best choice for. (More in the answers to this question, including mine.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Great. That's a better description. " if used for its purpose: Looping through the names of the enumerable properties of an object" .. Other people say.. Hey beginners don't ever use this it's harmful :D thank you dear – Abdurrahman Hafez Jan 07 '18 at 07:57