Back to all blogs

JavaScript for loop

April 28th, 2024 - 3 min read

We want to iterate through an array or an object in JavaScript, what approaches we can use; pros and cons of each?


Traditional for loop

const nums = [1, 2, 3];
 
for (let i = 0; i < nums.length; i++) {
  console.log(nums[i]);
}

Output

1
2
3

Pros:

  • Easy to remember (Similar syntax with other programming languages).
  • Can apply continue (skip current iteration and move to the next one) or break (end the loop).
  • Can await the current iteration before the next iteration.

Cons:

  • Take more time to write.
  • Don't have direct access into the element, we need to access via index nums[i].

Questions:

  • Can we use for (var i = 0; i < nums.length; i++)? -> We shouldn't, var will hoist i to the outer scope so all the iterations use the same reference of i:
const nums = [1, 2, 3];
 
for (var i = 0; i < nums.length; i++) {
  setTimeout(() => {
    console.log(nums[i]);
  }, 0);
}

Output

undefined
undefined
undefined

Explanation: i after the for loop is 3, and nums[3] = undefined

forEach

const nums = [1, 2, 3];
 
nums.forEach((num, index) => {
  console.log(index, num);
});

Output

0 1
1 2
2 3

Pros:

  • Quick to write.
  • Can access both value and index quickly.

Cons:

  • Cannot use break or continue; return expression only terminates the current iteration, not ending the outer function.
  • Cannot not await the current iteration before the next iteration.

for (const ... of ...)

const nums = [1, 2, 3];
 
for (const num of nums) {
  console.log(num);
}

Output

1
2
3

Pros:

  • Quick to write.
  • Can apply continue (skip current iteration and move to the next one) or break (end the loop).
  • Can await the current iteration before the next iteration.

Cons:

  • Don't have direct access to the index, we need to access via index for (const [index, num] of Object.entries(nums)).

Questions:

  • Can I use for (let num of nums) -> Yes, if you want to modify num inside the for loop (but mostly, I think you shouldn't).

for (const ... in ...)

const nums = {
  a: 1,
  b: 2,
  c: 3,
};
 
for (const key in nums) {
  console.log(key);
}

Output

a
b
c
const nums = [1, 2, 3];
 
for (const key in nums) {
  console.log(key);
}

Output

0
1
2

Pros:

  • Simple syntax to loop through properties inside an object.

Cons:

  • We need to understand this carefully because it's easy to create unexpected behaviors:
    • Example: nums.__proto__.test = 1 -> test is included in the iteration as a property -> We can use Object.hasOwn(nums, 'test') to check if test is not from prototype.

Safer way to loop through an object: Object.entries

const nums = {
  a: 1,
  b: 2,
  c: 3,
};
 
for (const [key, value] of Object.entries(nums)) {
  console.log(key, value);
}

Output

a 1
b 2
c 3