I don't understand how the console.log(x)
works in the situation below.
I understand that addEventListener("keydown", function)
means when keydown, do the function (here print to console).
However, I really can't grasp how things work when we pass a parameter to an anonymous function(here x
) in method addEventListener(), then implementing console.log(x) will print the keydown
event to console.
document.addEventListener("keydown", function(x) {
console.log(x); // e.g. KeyboardEvent {isTrusted: true, key: "x", code: "KeyX", location: 0, ctrlKey: false, …}
});
same with
(one small notice that with event
I can just use function()
and it's still working):
document.addEventListener("keydown", function() { //here no need to input `event` as parameter
console.log(event); // e.g. KeyboardEvent {isTrusted: true, key: "x", code: "KeyX", location: 0, ctrlKey: false, …}
});
but
document.addEventListener("keydown", function() { //no parameter
console.log(x); // Uncaught ReferenceError: x is not defined
});
Read more here: https://stackoverflow.com/questions/66279016/in-the-method-addeventlistener-how-does-passing-a-parameter-x-to-anonymous-func
Content Attribution
This content was originally published by aanhlle at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.