FOR...OF IN JAVASCRIPT – UNDERSTANDING FOR LET X OF

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:




javascript






for (let x of iterable) { // code block }


This loop means: “For each value in the iterable, assign it to x, and run the code block.”


Let’s break it down!







 Syntax of for...of



javascript






for (let x of iterable) { // Use x inside this block }




  • let declares a new variable x 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



javascript






const fruits = ["apple", "banana", "mango"]; for (let fruit of fruits) { console.log(fruit); }


Output:




nginx






apple banana mango






 Example 2: Iterating Through a String



javascript






const word = "hello"; for (let letter of word) { console.log(letter); }


Output:




nginx






h e l l o






 Example 3: With let x – Understanding Scope



javascript






const numbers = [1, 2, 3]; for (let x of numbers) { console.log("Current value of x:", x); }




  • let x ensures that each iteration has its own block-scoped variable x.




  • 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:




javascript






const arr = [10, 20, 30]; for (let index in arr) { console.log(index); // 0, 1, 2 (index) } for (let value of arr) { console.log(value); // 10, 20, 30 (value) }






 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 or forEach() 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.

Report this page