I need explanation of forEach, for-in, for-of loop in Jacascript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I need explanation of forEach, for-in, for-of loop in Jacascript

And how to use them

17th May 2020, 6:17 PM
Awojobi Godfrey
Awojobi Godfrey - avatar
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 :))
17th May 2020, 6:45 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 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.
18th May 2020, 7:07 AM
Calviղ
Calviղ - avatar