JavaScript Code

JavaScript for…of Loop


for…of loop

for (item of iterable) {
  //code
}
  • for is keyword
  • item is variable to hold the current item of the iterable during iteration
  • iterable is any valid iterable object like array, string, etc.
  • code is any valid JavaScript code

for...of loop iterates over the items of the iterable, and executes the block of code for each item

Examples

1. for…of loop to iterate over the items of an array numbers

const numbers = [4, 10, 5, 8, 64];
for (let num of numbers) {
    console.log(num);
}

2. for…of loop to iterate over the characters of a string myStr

const myStr = 'hello';
for (let ch of myStr) {
    console.log(ch);
}