Help! to clear JavaScript a concept

This is the link to my project: codepen link
So, on the 26th line of JavaScript code , element and index have been passed as arguments, JS has to insert the element and index of the respective note cards into their text.
My question is that if element and index have not been defined anywhere before,then how does JS know for each note card what it’s element and index is, how does it assign values dynamically to different note cards. Does that make sense?
Thank you for your time!

I think I understand the question. In that line of code, you are using the forEach array method. The element and the index are passed from the array itself as arguments.

As it iterates over the array, it looks at each item in the array and passes the content of each item in the array as well as the position where the content is located, into the anonymous function.

function (element, index) {
    html += `<div class="noteCard my-2 mx-2 card" style="width: 18rem;">
        <div class="card-body">
            <h5 class="card-title">Note ${index + 1}</h5>
            <p class="card-text"> ${element}</p>
            <button id="${index}" onclick="deleteNotes(this.id)" class="btn btn-primary">Delete Note</button>
        </div>
    </div>`;
  }

The parameters of that function, element and index are solely placeholders and are just used to name the data that the function receives from the array, which will be used to work with the data passed into the function.
It’s telling the function, “Hey, I’m going to give you two bits of information, and I want you to refer to them as element and index, respectively”

In all honesty, you could name it whatever you want and it would still work as long as those are the names used in the function’s body.

for example:

function (jelly, doughnut) {
    html += `<div class="noteCard my-2 mx-2 card" style="width: 18rem;">
        <div class="card-body">
            <h5 class="card-title">Note ${doughnut + 1}</h5>
            <p class="card-text"> ${jelly}</p>
            <button id="${doughnut}" onclick="deleteNotes(this.id)" class="btn btn-primary">Delete Note</button>
        </div>
    </div>`;
  }

It’s really just a looping function.
There’s more to it under the hood, but that’s the gist of it.

For more information you can visit MDN Array.prototype.forEach()

1 Like

Thank you for answering , but how does JavaScript know which bit of information from among the two is a number to be assigned to index and text to be assigned to element. Cause output is different if i switch their positions like function (index , element) so are they supposed to be declared in a certain order like, first element then index because the array first provides a string and then a number?

yes they are supposed to be declared in the order required by the forEach function which is well documented online. (and the previous post gave you a link to it)

1 Like