passing parameters to anonymous functions Javascript

Viewed 103

I could not understand why you do not need to pass the parameter name to the anonymous function inside the addEventListener. Why do you need to pass e , but not name. I mean line 6 at the end of the line, function(e)

let btn = document.querySelector(".test-btn");
  function firstFunction(e,name){
    e.preventDefault();
    btn.innerHTML = name;
  }
  btn.addEventListener("click",function(e){
    firstFunction(e, "Elon");
  });
1 Answers

Function parameters allow a block at some position, let's say block A, to send information to a function block at some other position, let's say Block B. When you pass a parameter, information can flow from A to B if A sends an argument and B accepts an argument.

Here, part of the information being sent is initialized inside the click callback:

btn.addEventListener("click",function(e){
  firstFunction(e, "Elon");
});

The e, the click event, is initialized by the browser and sent to the callback. But then the "Elon" string is created inside the callback. Finally, the callback does firstFunction(e, "Elon") to pass both pieces of information to the firstFunction, or the B block.

Because the extra information being passed along is created inside the click callback, and not by the caller of the click callback, the click callback only accepts one parameter, the event.

Related