for...of in JavaScript – Understanding for let x of
for...of in JavaScript – Understanding for let x of
Blog Article
In JavaScript, the for...of
loop is a powerful and modern way to iterate over iterable objects like arrays, strings, sets, and more. You often see it written as:
This loop means: “For each value in the iterable, assign it to x
, and run the code block.”
Syntax of for...of
let
declares a new variablex
for each iteration.
of
is the keyword that pulls values from the iterable.
iterable
can be arrays, strings, maps, sets, etc.
Example 1: Iterating Through an Array
Output:
Example 2: Iterating Through a String
Output:
Example 3: With let x
– Understanding Scope
let x
ensures that each iteration has its own block-scoped variablex
.
You can safely use
x
inside the loop without affecting outside code.
Difference Between for...in
and for...of
Loop Type | Iterates Over | Use For... |
---|---|---|
for...in | Property keys | Objects |
for...of | Property values | Arrays, strings, sets |
Example:
When to Use for (let x of ...)
When you want the values from arrays or strings.
When order matters and you want to use a clean loop.
When working with Sets and Maps.
When avoiding traditional
for
orforEach()
syntax for readability.
Final Summary
Component | Meaning |
---|---|
for | Starts the loop |
let x | Declares a new variable per loop |
of | Gets each value from the iterable |
Using for (let x of ...)
makes your code more readable, cleaner, and less error-prone, especially when working with iterable data in JavaScript.