DEV Community

Cover image for Everything to know about for...in and for...of
Ambroise BAZIE
Ambroise BAZIE

Posted on • Updated on

Everything to know about for...in and for...of

for...of vs for...in

Everything you should know before using for...in or for...of

for...of

for...of statement creates a loop iterating over
iterable objects, including: build-in String, Array,array-like objects (e.g: arguments or NodeList ), TypedArray, Set, Map, and user-defined iterables. It invokes a custom iterable hook for the statements to be executed for the value of each distinct property of the object.

Iterate over Array

let l = [20, 30, 40];
// use let 
for (let item of l) {
    item += 1
    console.log(item)
}
// 21
// 31
// 41

// use const 
for (const item of l) {
    console.log(item)
}
// 20
// 30
// 40
Enter fullscreen mode Exit fullscreen mode

Iterate over NodeList

Iterate through li with class .list and adding .active

let lis = document.querySelectorAll('ul > li.list');

for (let li of lis){ 
li.classList.add('active');
}
Enter fullscreen mode Exit fullscreen mode

Iterate over String

let str = 'hello';

for (let char of str) {
    console.log(char)
}
// h
// e
// l
// l
// o
Enter fullscreen mode Exit fullscreen mode

Iterate over Set and Map

// Set
let list = [1, 2, 2, 3, 4];
let set = new Set(list);

for (let i of set) {
    console.log(i);
}
// 1
// 2
// 3
// 4

// Map
let map = new Map([['milk', 10], ['potatoes', 20]]);

for (let [key, value] of map) {
    console.log(key, value) 
}
// milk 10
//  potatoes 20
Enter fullscreen mode Exit fullscreen mode

for...in

for...in can be applied on iterable, object and return the index or key of each element.

let arr = [1, 3, 4];

let obj = { milk: 10, grappes: 23 };

// work well
for (let key in arr) {
  console.log(key);
}
// Output:
// 0
// 1
// 2

// will return keys
for (let key in obj) {
  console.log(key);
}
// Output:
// milk
// grappes

Enter fullscreen mode Exit fullscreen mode

Thank You

Top comments (0)