In each loop, we get different execution environment
This is not true in while loop
for…of
This is used to iterate over Iterable object such as Array, String, Map, Set and so on.
Iterable objects have [Symbol.iterator] property defined
Examples:
const arr = [10, 20, 30];for (let val of arr) { console.log(val);}// 10// 20// 30const str = "boo";for (let c of str) { console.log(c);}// b// o// oconst m = new Map([["a", 1],["b", 2],["c", 3]]) for (let entry of m) { console.log(entry);}// ['a', 1]// ['b', 2]// ['c', 3]
In case of Non-Iterable Objects it throws error
const obj = { "a": 1, "b": 2};for (let x of obj) { console.log(x);}// TypeError: obj is not iterable
for…in
This is used to iterate over enumerable properties of object
const obj = { "a": 1, "b": 2};for (let x in obj) { console.log(x);}// a// b
In case of string and array it gives out indices:
const arr = [10, 20, 30];for (let val in arr) { console.log(val);}// 0// 1// 2const str = "boo";for (let val in str) { console.log(val);}// 0// 1// 2
If extra properties are defined, they also get iterated over:
const arr = [10, 20];arr.hello = "Hello";for (let x in arr) { console.log(x);}// 0// 1// hello
forEach()
The forEach() method can be used to iterate over array using callback
[10,20].forEach((v) => console.log(v));// 10// 20
this in loops
this is taken from parent context in for, for...of, for...in and regular loops
forEach callback:
if function expression is used, this is different
if arrow function is used this is taken from parent context
Async loop execution
We can iterate over using async-await using for, for...of, for...in
forEach do not work as expected in case of asynchronous execution and so is the case with other callback based iterative methods.
forEach callback is not promise-aware and do not return anything hence async-await cannot be used
async function asyncFn() { const arr = ['a', 'b', 'c']; for (const el of arr) { await new Promise(resolve => setTimeout(resolve, 1000)); console.log(el); }}