You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中for-of是否为最佳实践?迭代器该用var/let/const哪一个?

Great question—let's break this down clearly, since following iteration best practices is key to writing clean, performant JavaScript.


Is for-of a Good Replacement for for-in?

Absolutely. for-of was introduced in ES6 specifically to fix the pain points of for-in, making it the go-to choice for iterating over iterable objects like arrays, NodeLists (your cells collection falls into this), strings, Maps, Sets, and more.

Here's why it’s way better than for-in:

  • It only iterates over the actual elements of the iterable, not inherited prototype properties (a common gotcha with for-in that leads to unexpected behavior).
  • It’s optimized for performance, especially with DOM collections like NodeLists—modern browsers even tune for-of to match the speed of traditional for loops in many cases.
  • It has a clean, readable syntax that makes your code easier to maintain.

Ditching for-in for for-of (when you need to iterate over elements, not object properties) is fully aligned with modern JS best practices.


Should You Use var, let, or const for the Iterator Variable?

This depends on whether you need to reassign the iterator variable inside the loop block. Let’s break down each option:

Why Avoid var?

Never use var here—it’s a relic of pre-ES6 JavaScript with major scoping flaws. var uses function-level scoping instead of block-level scoping, so:

  • The iterator variable leaks outside the loop’s scope.
  • All loop iterations share the same variable reference. This causes critical bugs in asynchronous code (like your addEventListener example): if you used var iterator, every click handler would log the last element in cells, because the callback runs after the loop finishes, and iterator would already point to the final value.

When to Use let?

Use let only if you need to reassign the iterator variable inside the loop. For example:

for (let iterator of cells) {
  iterator = modifyElement(iterator); // Reassigning the variable
  iterator.addEventListener('click', () => console.log(iterator));
}

let creates a new variable binding for each loop iteration, so each callback gets the correct value for that cycle.

When to Use const?

Prefer const whenever possible—this is the most idiomatic choice for modern JS. const declares a block-scoped variable that cannot be reassigned.

In your example, you’re only reading properties/methods of iterator (calling addEventListener), not reassigning it. Using const here:

  • Makes your code safer: you can’t accidentally overwrite iterator with a different value inside the loop.
  • Communicates intent clearly to other developers: "this variable won’t change during this iteration."

Just like your sample code shows, const works perfectly here—each loop iteration gets its own const-declared iterator pointing to the current cells element, so every click handler logs the correct element.


Analyzing Your Example Code

Your code is actually following best practices:

for (const iterator of cells) {
  iterator.addEventListener('click', function (event) {
    console.log(iterator);
  });
}
  • Using for-of is the right call for iterating over the cells NodeList.
  • Using const is ideal here because you don’t reassign iterator—each callback captures the correct element from that iteration, no bugs from shared variable references.

内容的提问来源于stack exchange,提问作者Abdurrahman Hafez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:34:02