How does the compiler know that “element” refers to the value of array(prices)
?
let prices= ["cartoon", "what" , "sanjay"];
prices.forEach(loop);
function loop(element , what ){
document.write( what+":"+ element + "<br>");
}
How does the compiler know “what” is the index of the array(prices)
and “element” is the value of array(prices)
when I have not defined let element=prices.value()
something or let what =price.charat()
I was expecting an error since the “element” and “what” variable are not defined.
2
Answers
prices.forEach(loop)
is roughly equivalent toWhen you see it this way, you can see how the arguments are being passed to the function.
element
andwhat
are the parameters of the functionloop
. This makes them defined inside the function. The "callback" functionloop
is called by theArray.prototype.forEach()
method. While going through the arrayprices
one by one, the method supplies each element and index ofprices
and the array-reference toprices
as the three arguments to this function.Referring to the @Oarchlight’s comment under this answer:
If you want to "write" only the idex of all the elements in
prices
you can do something like below:You should avoid using
document.write()
in your script as it could overwrite existing things on your page. Instead I included a.map()
based approach for placing theindex
values on the page by setting theinnerHTML
property of the#output
DOM element.