+ 1
I need explanation of forEach, for-in, for-of loop in Jacascript
And how to use them
2 Answers
+ 3
forEach :
const array = [1,2,3,4,5];
array.forEach(num => { console.log(num); })
forEach method takes a callback to execute. The argument corresponds with array element.
for-in :
for (const num in array) {
console.log(num);
}
While using for-in loop, in each iteration a new const 'num' is created.
for (let num of array) {
console.log(num);
}
In for-of loop, in each iteration the num is replaced/reassigned by itself. That means if you use const data type, it will give an error. Because constant can not be changed.
Hope that helps :))
+ 2
https://code.sololearn.com/W4fVU4QmTw0D/?ref=app
Please note that for in loop is iterating the index of the array, whereas for of loop is iterating the element of the array.