Search code examples
javascriptjavascript-objects

what does .key mean at the end of keys[keyDownEvent.key]?


I am working on building a game from a tutorial. I am on the bit where I am adding event listeners to my program. The instructor added what I think is a property to the keys object, but I can't be sure. If this piece of code does add a new property, what exactly does the .key do? What is its functionality? I have tried printing keys[keyDownEvent.key] to the console, but it did not clarify anything to me. I really hope you can help. Thanks in advance!

Here is my code:

// Create keys object and initialise keys press as false
let keys = {
    arrowUp: false,
    arrowDown: false,
    arrowLeft: false,
    arrowRight: false
}
// Create event listeners
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);

function keyDown(keyDownEvent) {
    keys[keyDownEvent.key] = true;
}

function keyUp(keyUpEvent) {
    keys[keyUpEvent.key] = false;
}

Edit: thought it might be worth linking the video https://www.youtube.com/watch?v=7NJxZCgjnmI


Solution

  • The event listeners provide an Event object (specifically, a KeyboardEvent here) which contains info about the fired event. event.key is a KeyboardEvent property which tells you what key fired that event.

    The event object looks something like this:

    {
      ...
      target: <div>,
      key: 'ArrowUp'
    }