0

I' currently studying js and DOM and there is something about the eventListener I really don't understand.Here's my problem. I create a function that takes one argument, check if that arguments is equal to W , A or S and play a sound.There's nothing wrong with this function,it works perfectly.

function playSound(key) {
  switch (key) {
    case "w":
      var crash = new Audio("sounds/crash.mp3");
      crash.play()
      break;

    case "a":
      var kickBass = new Audio("sounds/kick-bass.mp3");
      kickBass.play()
      break;

    case "s":
      var snare = new Audio("sounds/snare.mp3");
      snare.play()
      break;

    default:

Now I'd like to start this function whenever the "keydown" event is called. The question is: why is the following code working

document.addEventListener ("keydown" , function(event) {
   playSound(event.key);
};

while this one is not?

document.addEventListener ("keydown" , playSound(event.key));

Why do I need an anonymous function to call another function when I could call the function I need straight away?I'm very confused

  • the addEventListener function accepts two parameters. First the event name, second listener function. In the second example you're passing the return value of `playSound` function which is `void` when `addEventListener` expects listener function – Rhymond Apr 05 '22 at 11:22
  • `addEventListener` has certain signature, meaning it expects parameters to be of a specific type, [see MDN for `addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters). The second parameter for `addEventListener` must be either a `function` or implement the `EventListener` interface. In your second example, `playSound` already executes the function and returns a value - this value is neither a function nor an EventListener. – b2m9 Apr 05 '22 at 11:23
  • @Rhymond - `undefined`, not `void`, and `addEventListener` has more than two parameters (the third is just optional): https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#browser_compatibility :-) But yeah, fundamentally, that's the issue. – T.J. Crowder Apr 05 '22 at 11:23

0 Answers0