Stopping eventListener function

Hello everyone. In my current project, I am adding an event listener that listens for a keydown event and runs a function that plays audio files corresponding to a matching attribute within some HTML audio tags. I was instructed to include some additional code to ‘stop’ the function. Here is my code:

    const audio = document.querySelector(`audio[data-key="${e.code}"]`); // selects any HTML audio tags with data-key attribute values that match the corresponding keydown event's event.code value. Assigns to variable named 'audio'.
    console.log(audio); // prints that attribute value to console; prints 'null' if there is no matching audio tag with that attribute value. However, we can add another line of code to stop the function altogether:
    if(!audio) return; // if there is no tag equal to the current value of audio, stop function altogether.; //otherwise, if value of variable 'audio' matches an audio tag, play it's corresponding sound file.

I’m curious about why it’s best to include the if(!audio) return; segment to stop the function for keydown events that don’t match an audio file. I noticed the sound files play properly when the correct keys are pressed, and nothing plays or seems to interfere when other keys are pressed by the user. I did notice an error code does appear in the console behind the scenes because it cannot play a file for certain keys: “app.js:35 Uncaught TypeError: Cannot read property 'play' of null”.

Does omitting this line of code to stop the function really have any effect on the user or my program, aside from the error in the console? I just want to understand the logic of why we take the extra step of stopping the function, especially since it isn’t a loop. I’m just trying to understand how this is beneficial beyond avoiding the “cannot read property of 'play” errors in the console.

querySelector will return null if the selector does not match an element on the page. If you call and audio is null you will get an error.

There is no good reason not to check the element before calling the play method. Just because an error does not crash the app or prevent it from working properly doesn’t mean you shouldn’t handle the error or prevent it from happening in the first place.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.