1

I'm just trying to understand the logic behind this code:

window.onkeydown = function () {
    handler(event);
};
function handler(event)
{
    console.log(event.key); // this works!
}

Shouldn't the event handler be declared with the event argument included in the anonymous function? Like so:

window.onkeydown = function (event) {
    handler(event);
};

I understand that browsers automatically pass the event to the handler, but still I find it weird that assigning an anonymous function without arguments still works. Is this a normal behaviour?

1
  • 1
    Internet Explorer traditionally did not pass the event object as a parameter. Instead, it's a global variable that's updated when an event occurs. That was a horrible design decision but most browsers (Firefox excepted) now imitate that behavior. Commented Jan 6, 2020 at 14:15

1 Answer 1

1

Why are event argument optional in anonymous functions in Javascript?

They aren't, cross-browser. Microsoft had a global event that was set to the current event before calling handlers using their attachEvent (and onxyz) handlers. The DOM standard went another way: passing event as an argument.

Chrome and some other browsers do both, so that Microsoft-specific code works on them. But not all browsers do. Firefox doesn't, for instance, unless you set a special preference in your user preferences (details).

The key takeaway is: Use modern event handling (addEventListener, etc.), which is supported in all browsers other than IE8 and earlier, and declare the event parameter to the function:

window.addEventListener("keydown", handler);

// ...

function handler(event) {
    // ...
}

or (the function name is optional, but useful in error call stacks):

window.addEventListener("keydown", function handler(event) {
    // ...
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation! I actually tried the code on a fresh installed Firefox 71 and it also works! I guess they reenabled that global event by default in recent versions... Don't really see the point, it seems messy and poor design...
@nrgribeiro - The point to the global? Agreed, the DOM standard's way is the way to go. But I guess Mozilla decided that they wanted to get rid of all those "why does this code work everywhere but Firefox?" complaints. :-) Or it's getting adopted as a standard, a lot of old legacy stuff is...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.