Table of contents
No headings in the article.
The for..of loop in JavaScript allows us to iterate over iterable objects (arrays, sets, maps, strings etc).
for...of loop in array:
const names=["sheldon","Leanord","Raj","Howard"]
for ( let name of names ) {
console.log(name);
}
output:
sheldon
Leanord
Raj
Howard
Let's try looping the objects in the same way as we did with array,
const Person={name:"Joe",age:22}
for ( let name of names ) {
console.log(name);
}
output:
*Uncaught TypeError: names is not iterable*
We have received the obvious error as objects are not iterable in javascript so in order to loop over the objects we are supposed to use Object.keys().
Outputting keys using Object.keys():
const Person = { name: "Joe", age: 22 };
for (const name of Object.keys(Person)) {
console.log(name);
}
output:
name
age
Outputting Values using Object.values():
const Person = { name: "Joe", age: 22 };
for (const name of Object.values(Person)) {
console.log(name);}
output:
Joe
22
Cool yeah!!! We have fetched the keys and values of our objects. But do you know in reality we are only looping over array in an indirect way. Let's see how???
const Person = { name: "Joe", age: 22 };
const key=Object.keys(Person);
const value=Object.values(Person);
console.log(key , value)
output:
['name', 'age'], ['Joe', 22] // received array as an output, so we are just iterating over array behind the scenes
So far we have fetched key and value of objects individually. But to loop over entire object we need entries. entries are key and values together.
const Person = { name: "Joe", age: 22 };
const person=Object.entries(Person);
console.log(person)
We will receive arrays having keys and values together as an output. Now let's print both keys and values together using Object.entries() method.
const Person = { name: "Joe", age: 22 };
for(const [key,value] of Object.entries(Person)){ // performed array destructuring
console.log(key +' : '+value)
}
output:
name : Joe
age : 22