Loop over objects
for..in statement
for..in
statement is used for iterating keys of an object.
js
const person = {
name: 'john',
age: 18
};
for (let key in person) {
console.log(key)
}
// name
// age
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
key of Array
Array
is also object
. But its keys are are indices.
js
const array = [1, 12, 123];
for (let key in array) {
console.log(key);
}
// 0
// 1
// 2
1
2
3
4
5
6
7
2
3
4
5
6
7
for..of statement
Use for..of
statement to iterating the values of properties.
the object to be iterated must be iterable
js
const person = {
name: 'john',
age: 18
};
for (const prop of person) {
console.log(prop);
}
// 'john'
// 18
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
You might notice the occurrences of const
and let
in for..in
and for..of
loop.
let
allows the mutation of variable in scope.const
forced the variable in scope immutable.