2

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");
  });
2
  • 1
    Because that function is a callback from the event listener, which only provides the event object as the first positional argument. The name argument is used by your firstFunction method. Commented Dec 28, 2020 at 23:56
  • 1
    You don't "pass e", it's the browser that passes it, just because of how the event is defined in the specs. Commented Dec 29, 2020 at 0:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.