I'm trying to understand this unexplained code from Eloquent Javascript :
function trackKeys(keys) {
let down = Object.create(null);
function track(event) {
if (keys.includes(event.key)) {
down[event.key] = event.type == "keydown";
event.preventDefault();
}
}
window.addEventListener("keydown", track);
window.addEventListener("keyup", track);
return down;
}
var arrowKeys =
trackKeys(["ArrowLeft", "ArrowRight", "ArrowUp"]);
I think I understand how the inner function track
will maintain a reference to down
and keys
because it is a closure, but I'm lost at return down;
Will that return value be a reference to the exact same down
the callbacks are accessing? I don't understand; I thought local variables could only be accessed by inner functions?
Follow-up: what if down were a primitive data type and not an object, would this still work?