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
Output
Pros:
- Easy to remember (Similar syntax with other programming languages).
- Can apply
continue
(skip current iteration and move to the next one) orbreak
(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 hoisti
to the outer scope so all the iterations use the same reference ofi
:
Output
Explanation: i
after the for loop is 3, and nums[3] = undefined
forEach
Output
Pros:
- Quick to write.
- Can access both value and index quickly.
Cons:
- Cannot use
break
orcontinue
;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 ...)
Output
Pros:
- Quick to write.
- Can apply
continue
(skip current iteration and move to the next one) orbreak
(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 modifynum
inside the for loop (but mostly, I think you shouldn't).
for (const ... in ...)
Output
Output
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 useObject.hasOwn(nums, 'test')
to check iftest
is not fromprototype
.
- Example:
Safer way to loop through an object: Object.entries
Output