Course contentsShow
← Web Development
Lesson 751 of 2,98213. DOM EventsFree lesson

Keyboard Event Properties: key, code, and keyCode

Accessing which key was pressed using modern key and code properties versus deprecated keyCode.

Keyboard Event Properties: key, code, and keyCode

You'll learn how to identify which key a user pressed using modern and legacy properties.

Understanding the Key Properties

When a user presses a key, the KeyboardEvent object gives you several ways to identify that key. Think of these properties as different "name tags" for the same key—each tells you something slightly different.

The Modern Approach: key and code

event.key tells you what character was typed. For the letter "A", it returns "A" (uppercase) or "a" (lowercase) depending on Shift. For special keys, it returns descriptive strings like "Enter", "Escape", or "ArrowUp".

document.addEventListener('keydown', function(event) {
  console.log(event.key); // "a", "A", "Enter", "Shift", etc.
});

event.code tells you the physical key position on the keyboard. It always returns the same value regardless of keyboard layout or modifiers. For example, pressing the "A" key always returns "KeyA", whether you type "a", "A", or even "q" on a French keyboard.

document.addEventListener('keydown', function(event) {
  console.log(event.code); // "KeyA", "Enter", "Space", "ArrowLeft", etc.
});

The Deprecated Property: keyCode

event.keyCode returns a numeric code (like 65 for "A"). This property is deprecated and unreliable across different browsers and keyboards. Avoid using it in new code.

When to Use Which

Use event.key when you care about what the user typed (text input, shortcuts like "Ctrl+S").

Use event.code when you care about physical key location (game controls where "WASD" should work regardless of keyboard layout).

Key Takeaway: Use event.key for character input and event.code for physical key position; avoid the deprecated event.keyCode in modern code.