Is using event.target necessary when capturing input data?

Viewed 81

I'm currently following a tutorial about Javascript events. Basically, what the instructor is walking us through is how to listen to user input data from the HTML input tag using the keyup Javascript event and then logging the value on the console.

Here's the code snippet:

document.getElementById("searchInput").addEventListener("keyup", function(event) {
    let searchQuery = event.target.value.toLowerCase();
    console.log(searchQuery);
});

It's straightforward, however, I'm curious about the significance of adding the event parameter and accessing the target property of such event. I went ahead and removed the event parameter, as well as the target property, and made it so as to log the value, too, and, as far as I am aware, it behaved identically.

document.getElementById("searchInput").addEventListener("keyup", function () {
    let searchQuery = document.getElementById("searchInput").value.toLowerCase();
    console.log(searchQuery);
});

Is there a unique reason why the instructor chose to do the former or is it simply for brevity reasons?

1 Answers

It’s useful if you want to write a more general function that would work with whatever element you pass into it. Currently you are specifying the id of the element you’d like to access within the function. But at some point you may want to write a function that you can reuse with multiple elements at once, this is where event.target comes in.

Related