What exactly is the parameter e (event) and why pass it to JavaScript functions?

The e is short for event

The simplest way to create an event is to click somewhere on the page.

When you click, a click event is triggered. This event is actually an object containing information about the action that just happened. In this example’s case, the event would have info such as the coordinates of the click (event.screenX for example), the element on which you clicked (event.target), and much more.

Now, events happen all the time, however you are not interested in all the events that happen. When you are interested in some event however, it’s when you add an event listener to the element you know will create events[1]. For example you are interested in knowing when the user clicks on a ‘Subscribe’ button and you want to do something when this event happens.

In order to do something about this event you bind an event handler to the button you are interested in. The way to bind the handler to the element is by doing element.addEventListener(eventName, handler).

eventName is a string and it’s the name of the event you are interested in, in this case that would be 'click' (for the click event).

The handler is simply a function which does something (it’s executed) when the event happens. The handler function, by default, when executed is passed the event object (that was created when the event/action you are interested in happened) as an argument.

Defining the event as a parameter of your handler function is optional but, sometimes (most times), it is useful for the handler function to know about the event that happened. When you do define it this is the e you see in the functions like the ones you mentioned. Remember, the event is just a regular javascript object, with lots of properties on it.

Hope that helped.

For more info read Creating and Triggering Events

As for your 3rd question, now you should know you cannot do that, because e only exists when an event happens. You could have the handler function, which has access to the e object when it gets executed, to store it in some global variable and work on that.

[1] That is not exactly correct, but it’s simpler to understand. The more correct thing to say there is “add an event listener to the element you know will have events flow through it”. See this for more information

Leave a Comment