What is the function of the parameter 'e' (event) in a JS callback function?

I have used input.value in the following code. And in another code, I will use e.target.value and will pass ‘e’ as a parameter to the function. But both of them do exactly the same thing. What is the difference between them? Is one more efficient than another? What is the ‘event’ even used for? Can anyone explain this please?


<input type="text" id="input">
<h3 id="h3"></h3>


var input = document.getElementById('input');
var h3 = document.getElementById('h3');
var body = document.querySelector('body');

input.addEventListener('keyup', function(){
body.style.backgroundColor = input.value;

The parameter is an object that is created when the event happens, had a load of useful information about the event.

What you’ve done there is hold a reference to that input, then when the event happens, you are checking what the value of it is. So there’s nothing wrong with that per se

If you use e.target.value, then you don’t need to keep that reference to the input around, the event object, which is always available to the callback, will have that information already, guaranteed to be up to date.

Normally you’d want to use the event object. You normally (although everything is context-specific) attach event handlers to some element higher up, rather than the input itself. For example, you could attach it to document. If you did that, event.target.value will still work (the keyup will have been triggered by that input). You can then just have one event handler, and if you have multiple inputs, you can check which one is the current target in the callback and act accordingly


The cool thing about coding is, most of the time there are different ways of achieving the same thing and each one having its pros and cons. Some more simple, fitting a simple purpose, some more thorough, when things are more complex, some having faster performance etc. In your case, its quite simple task, you alreayd have the input element stored as input, and if all you need is retrieve its value, using input.value is the simplest solution. However, there would be times when you might not have direct reference to the element you are dealing with(when designing a universal function to use as event handler for example, which would work for any element), or when you require additional data about the event, in such case comes to aid the event object passed to the event handler. Event handlers(the functions we pass to the addEventListener method) receive that event object by default and to access it, you just have to put a parameter to the function. The event object contains a wide range of data regarding the event, such as the event target, the element on which the event was called.

1 Like

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