My Image My Image

Ask me anything

What is the difference between and for..of loops?

Preffered Answer:

ONE The LOOP is mainly used to iterate over properties of an Objects.
In JAVASCRIPT Arrays are also Objects and each characters in an string have an index. So, we can use them also to iterate over Arrays and Strings also.

//Object example

const OBJ = {   'frontend developer': 'Thomas',   'designer': 'Mary',   'backend developer': 'Harry',   'engineering manager': 'Vikas' }   for(const key in obj) {   console.log(`${key}: ${obj[key]}`) } 

//Array example

const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager']; for(const index in array){   console.log(array[index]); }

//String example

const string = 'frontend developer'; for(const index in string){   console.log(string[index]); }

The for..of loop was introduced in ES6 and is used to iterate over Objects that have [Symbol.iterator] property. This includes array, strings, Map, Set and NodeList. They cannot be used to iterate over Objects are not iterable.

If we check the __proto__ of an array, we can find the [Symbol.iterator] property.

But it is not the case with Objects as it is not iterable.

Some use of for..of loop are below:

//Array example

const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager'];

for(const item of array){   console.log(item); }

//String example

const string = 'developer'; for(const char of string){   console.log(char); }

//Map example

const map = new Map();   const emp1 = {name: 'Vikas', Degree: 'MS'}; const emp2 = {name: 'Thomas', Degree: 'MBA'};   map.set(emp1, 'frontend developer'); map.set(emp2, 'engineering manager');   for(const [key, item] of map) {   console.log(key, '-', item); }

Write Your Comments or Explanations to Help Others