skip to Main Content

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


  1. prices.forEach(loop) is roughly equivalent to

    for (let i = 0; i < prices.length; i++) {
      loop(prices[i], i, loop);
    }
    

    When you see it this way, you can see how the arguments are being passed to the function.

    Login or Signup to reply.
  2. elementand whatare the parameters of the function loop. This makes them defined inside the function. The "callback" function loopis called by the Array.prototype.forEach() method. While going through the array prices one by one, the method supplies each element and index of prices and the array-reference to prices 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 pricesyou can do something like below:

    let prices= ["cartoon", "what" , "sanjay"];
    const out=document.getElementById("output")
    // using .forEach:
    prices.forEach(loop);
    
    // output to page, using .map:
    out.innerHTML=prices.map((_,i)=>i).join("<br>");
    
    function loop(_,index ){
        console.log(index);
    }
    <div id="output"></div>

    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 the index values on the page by setting the innerHTML property of the #output DOM element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search