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
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');
}
Iterate over String
let str = 'hello';
for (let char of str) {
console.log(char)
}
// h
// e
// l
// l
// o
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
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
Top comments (0)