forEach - don't understand, please, explain | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

forEach - don't understand, please, explain

In the forEach method, how does the interpreter understand that 'el' refers to the array index? В методе forEach, как интерпретатор понимает, что 'el' относится к индексу массива? var arr = [2, 3, 7, 8]; arr.forEach(function(el) { console.log(el * 2); });

25th May 2020, 1:17 PM
Сергей Куликов
Сергей Куликов - avatar
5 Answers
+ 10
• How to Use forEach() to Iterate an Array in JavaScript — https://dmitripavlutin.com/foreach-iterate-array-javascript/
25th May 2020, 5:24 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 6
the first parameter el is not index. the first parameter of the callback function is the element. the optional second parameter is index. the optional third parameter is the array itself.
25th May 2020, 2:20 PM
Gordon
Gordon - avatar
+ 4
This is just how the syntax works. You have called the .forEach method on the arr object already. It tells the interpreter to iterate through the arr and assign its consecutive values to el variable.
25th May 2020, 1:50 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 2
Thank you all for the answers, I figured it out. I was confused by the function definition inside the forEach method. Спасибо всем за ответы, разобрался. Меня смутило определение функции внутри метода forEach.
25th May 2020, 5:53 PM
Сергей Куликов
Сергей Куликов - avatar
25th May 2020, 2:34 PM
Ore
Ore - avatar