Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript: Challenge Making the Game Interactive handleKeydown() Solution

How does this code work?

Given that my app.js code for the 'keydown' event is identical to that shown in the video, how does the second part of my code for the Game.js 'handleKeyDown' method actually work...

handleKeyDown(keydown) {
    if(this.ready == true) {
      if(event.key === 'ArrowRight') {
        // Move right
      } else if (event.key === 'ArrowLeft') {
        // Move left
      } else if (event.key === 'ArrowDown') {
        // Move down
      }
    }
  }

I'm passing 'keydown' as the argument but referencing something different, 'event.key' when checking the arrow direction. I've done a console.log and it works but I'm puzzled why?

1 Answer

Steven Parker
Steven Parker
229,744 Points

Browsers generally create an "event" variable in a handler to reference the event object, as long as that name isn't already being used. But it's not good practice to rely on this. It's much better to use the reference explicitly passed in.

So while it works as-is, it would be cleaner to either rename the argument "keydown" to "event", or to change the references from "event" to "keydown".