for..of
loop
The for..of
loops are used for looping through iterable objects such as arrays:
let arr = [10, 20, 30]; for (let item of arr) { console.log(item); }
It also works with strings:
const greeting = "Hello!" for (const ch of greeting) { console.log(ch); }
for..in
loop
The for..in
loop allows you to iterate over keys of enumerable object properties.
const user = { firstName: "Yinzhi", lastName: "Cao" }; for (const key in user) { console.log(key, user[key]); }
It works with strings and arrays too, but iterates over the indices:
const arr = [10, 11, 12]; for (const key in arr) { // console.log(key); console.log(arr[key]); }
const greeting = "Hello!" for (const key in greeting) { // console.log(key); console.log(greeting[key]); }