Number Sorter - Help me understand the for each loop

Here’s a link to the lesson. You can ignore the step I’m on. This is about a bunch of code we made earlier in the lesson.

const updateUI = (array = []) => {
  array.forEach((num, i) => {
    const outputValueNode = document.getElementById(`output-value-${i}`);
    outputValueNode.innerText = num;
  })
//Example: [8,2,4,1,3]

My question is about the array.forEach function. It has two parameters, num and i. But how does it get the values for the parameters? Somehow it magically knows that the num parameter is the value and the i parameter is the position in the array. Using the example array, it knows that num=4 & i=2 for the 3rd value in the array.

1 Like

Hello!

The parameters are autofilled, meaning they are fed straight into the function in the background

.forEach (and other methods that take in a callback function) work this way

hope this solves your question!

2 Likes

so are you saying: any forEach function you make, if you give it two parameters, then the first parameter=value and second parameter=position?

Does that only apply if the parameters are called num and i specifically?

What if I gave the function 1 or 3 parameters? Is anything autofiiled?

the forEach callback function can take the following arguments (reference from the MDN site):

element

The current element being processed in the array.

index

The index of the current element being processed in the array.

array

The array forEach() was called upon.

You can pass any of these and call them anything you want so long as the order is respected.

2 Likes

And that order is the order you listed in?

But what if you only wanted one argument? Let’s say you wanted index. if I wrote
function.forEach((ind)=>{}), wouldn’t that autofill with “element”, since that’s the first one?

1 Like

the order is element, index, array
so if you want index, you have to write (el, ind) and then you can use the ind and ignore the el.

1 Like