Search code examples
javascripteventsargumentslanguage-design

JS: Why is the Event object accessible in event handlers without accepting it in a parameter?


While looking back over some JS I'd written in the past, I noticed that I was trying to access event.keyCode in an event handler, but my function's only parameter was e, not event. So, while I would expect to get a "Uncaught ReferenceError: event is not defined", I instead found that my script works as expected (at least in Chrome).

document.body.addEventListener('keyup', function(e) {
    if (event.keyCode === 13) {
        // ...
    }
});

In fact, if I place a console.log(e === event) in that handler, I get true. After a little testing (in a JS Bin) it seems like this must apply to every such event, making event another sort of "sly" local variable like arguments that appears in a function without asking for it in a parameter.

This makes me wonder:

  1. Are these the only two "sly" local variables?
  2. Is this behavior with event in Chrome consistent with other browsers & JS environments?

Solution

  • Depending on the browser, there is a global event variable that refers to the currently fired event.