-2

I was looking for javascript documentation and found this

const log = document.getElementById('log');

document.addEventListener('keydown', logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}

I don't understand how logkey function is working in addeventlistener . when I press a key, the console prints its code but logkey is not having any parameters in addeventlistener. How did it print e.code ?

  • 1
    Event object is passed by `addEventListener`. `logKey` is a callback function. – TheMaster Jun 26 '22 at 20:50
  • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener – evolutionxbox Jun 26 '22 at 20:51
  • Does this answer your question? [What is a callback function?](https://stackoverflow.com/questions/824234/what-is-a-callback-function) – TheMaster Jun 26 '22 at 20:55
  • 1
    Does this answer your question? [What exactly is the parameter e (event) and why pass it to JavaScript functions?](https://stackoverflow.com/questions/35936365/what-exactly-is-the-parameter-e-event-and-why-pass-it-to-javascript-functions) – pilchard Jun 26 '22 at 21:01

1 Answers1

0

You pass the function as a parameter to the eventListener. The eventListener calls the logKey function with the event as a function parameter.

See in the following example how a parameter is passed on to the function:

function func1(function_as_parameter){
  function_as_parameter('Shivam');
}

function helloWordFunction(name){
  console.log(`Hello ${name}!`);
}

func1(helloWordFunction); // Hello Shivam!
 
Erwin van Hoof
  • 957
  • 5
  • 17