In Javascript/jQuery what does (e) mean?

In Javascript/jQuery what does (e) mean?

Today I just wrote a post about “Why do we use the letters like “e” in e.preventDefault()?” and I think my answer will make some sense…

At first,let us see the syntax of addEventListener

Normally it will be: target.addEventListener(type, listener);

And the definition of the parameters of addEventlistener are:

type :A string representing the event type to listen out for.

listener :The object which receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function.

(From MDN)

But I think there is one thing should be remarked: When you use Javascript function as the listener, the object that implements the Event interface(object event) will be automatically assigned to the “first parameter” of the function.So,if you use function(e) ,the object will be assigned to “e” because “e” is the only parameter of the function(definitly the first one !),then you can use e.preventDefault to prevent something….

let us try the example as below:

Please click on the checkbox control.

the result will be : 5 and you will prevent the click event.

but if you remove the comment sign like :

you will get : 8 and an error:”Uncaught TypeError: e.preventDefault is not a function at HTMLInputElement. (VM409:69)”.

Certainly,the click event will not be prevented this time.Because the “e” was defined again in the function.

However,if you change the code to:

every thing will work propertly again…you will get 8 and the click event be prevented…

Therefore, “e” is just a parameter of your function and you need an “e” in you function() to receive the “event object” then perform e.preventDefault(). This is also the reason why you can change the “e” to any words that is not reserved by js.



Leave a Reply