Everything, Everywhere
Verified Specification | Standardized Formulas | Instant Precision
Secure & Private (Zero Data Retention) Free Access • No Sign-Up

For Loops

Loops allow you to run the same block of code multiple times with varying values.

Try It Yourself

      
📋 Copy JavaScript For-Loops & Iteration Cheat Sheet
const items = ["alpha", "beta", "gamma"];

// for...of (Values in Iterables: Arrays, Sets, Maps)
for (const [index, val] of items.entries()) {
  console.log(`${index}: ${val}`);
}

// for...in (Keys in Objects ONLY)
const config = { host: "localhost", port: 8080 };
for (const key in config) {
  if (Object.hasOwn(config, key)) {
    console.log(`${key} = ${config[key]}`);
  }
}

⚠️ 5 Fatal Traps & JavaScript Pitfalls

Trap #1: Using for...in on Arrays
for...in iterates over all enumerable property keys, including prototype methods and string indices in arbitrary order. Always use for...of or array methods for arrays.
Trap #2: Asynchronous Code Inside Array.prototype.forEach
forEach does NOT await promises! Passing an async callback runs promises concurrently and exits immediately before completion. Use for (const x of items) await ....
Trap #3: Closure Variable Leaks with var in Loops
Declaring for (var i = 0; ...) shares a single variable across all loop iterations, so asynchronous callbacks (like setTimeout) all log the final value. Use let to create per-iteration bindings.
Trap #4: Modifying Array Length During Iteration
Calling splice() or push() inside an index-based for loop alters the array length and shifts elements, causing items to be skipped.
Trap #5: Infinite Loop from Stagnant Counter Increment
Typing i-- instead of i++ locks the main browser thread in an infinite loop, crashing the tab.

💬 Frequently Asked Questions

What is the difference between for...of and for...in in JavaScript?
for...of iterates over values of iterable objects (Array, Map, Set, string). for...in iterates over enumerable keys/properties of an object.
How do you get both index and value in a for...of loop?
Call the .entries() method on the array: for (const [index, value] of array.entries()) { ... }.
Can you break out of an Array.prototype.forEach loop?
No. forEach executes for every element and cannot be terminated early with break or return. Use for...of or Array.prototype.some() instead.
What makes an object iterable in JavaScript?
An object must implement the Iterable protocol by providing a method at [Symbol.iterator] that returns an iterator object with a .next() method.
How can you iterate over an object using for...of?
Use Object.entries(obj), Object.keys(obj), or Object.values(obj) to convert the object into an iterable array.
Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement