Differences Between event.key vs event.code: Comprehensive Guide
Understanding semantic character output versus physical hardware key identity in W3C DOM Level 3 specifications.
event.key returns the semantic character value influenced by keyboard language, Shift keys, and Caps Lock (e.g. "a" vs "A"), whereas event.code returns the physical hardware key identity that never changes regardless of keyboard layout (e.g. always "KeyA" on both QWERTY and AZERTY). 1. event.key (Semantic Character Value)
Represents the printed text value rendered after OS processing. If a user presses number 1 while holding Shift, event.key becomes exclamation mark "!".
// Pressing 'a' without Shift:
event.key === "a"
// Pressing 'a' with Shift:
event.key === "A" 2. event.code (Physical Hardware Key Location)
Represents the physical key identity immune to Caps Lock, Shift, or regional keyboard layout settings. Ideal for web games (e.g. WASD navigation) so finger positioning remains globally consistent.
// First key in the second row:
event.code === "KeyA" // (QWERTY: A, AZERTY: Q)
// Spacebar:
event.code === "Space" | Key Press Condition | event.key Value | event.code Value | Recommended Usage |
|---|---|---|---|
| Press 'a' Key | "a" | "KeyA" | Use event.key for text field validation. |
| Shift + 'a' Key | "A" | "KeyA" | event.code remains stable for WASD games. |
| Press Spacebar | " " (Space) | "Space" | Use event.key === " " or event.code === "Space". |
| Press Enter Key | "Enter" | "Enter" / "NumpadEnter" | Use event.key === "Enter" for form submission. |
| Press Escape Key | "Escape" | "Escape" | Use event.key === "Escape" to dismiss modals. |
Migration Guide: Why event.keyCode is Deprecated
Modern W3C UI Events specifications replacing bug-prone arbitrary integer codes.
event.keyCode and event.which were formally deprecated because of cross-browser discrepancies, lack of mobile virtual keyboard support (where Android/iOS IME returns code 229), and confusion caused by binding characters to arbitrary ASCII numbers. // ❌ Using arbitrary numeric keyCodes
window.addEventListener('keydown', (e) => {
if (e.keyCode === 13) {
// Enter key
submitForm();
} else if (e.keyCode === 27) {
// Escape key
closeModal();
} else if (e.keyCode === 32) {
// Spacebar
jumpCharacter();
}
}); // ✅ Using semantic self-describing strings
window.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
submitForm();
} else if (e.key === 'Escape') {
closeModal();
} else if (e.key === ' ') {
// Or e.code === 'Space'
jumpCharacter();
}
}); JavaScript KeyCode & Keyboard Event Reference Table
Comprehensive reference table for common keys. Click any row to simulate that key in the studio above.
| Key / Function | event.key | event.code | keyCode (Deprecated) | Location | Category |
|---|---|---|---|---|---|
| ↵ Enter / Return | "Enter" | "Enter" | 13 | 0 (Standard) | Action |
| ␣ Spacebar | " " | "Space" | 32 | 0 (Standard) | Action |
| ⎋ Escape (Esc) | "Escape" | "Escape" | 27 | 0 (Standard) | Action |
| ⇥ Tab | "Tab" | "Tab" | 9 | 0 (Standard) | Action |
| ⌫ Backspace | "Backspace" | "Backspace" | 8 | 0 (Standard) | Action |
| ⌦ Delete (Del) | "Delete" | "Delete" | 46 | 0 (Standard) | Action |
| ↑ Arrow Up | "ArrowUp" | "ArrowUp" | 38 | 0 (Standard) | Navigation |
| ↓ Arrow Down | "ArrowDown" | "ArrowDown" | 40 | 0 (Standard) | Navigation |
| ← Arrow Left | "ArrowLeft" | "ArrowLeft" | 37 | 0 (Standard) | Navigation |
| → Arrow Right | "ArrowRight" | "ArrowRight" | 39 | 0 (Standard) | Navigation |
| ⇧ Left Shift | "Shift" | "ShiftLeft" | 16 | 1 (Left) | Modifier |
| ⌃ Left Control (Ctrl) | "Control" | "ControlLeft" | 17 | 1 (Left) | Modifier |
| ⌥ Left Alt / Option | "Alt" | "AltLeft" | 18 | 1 (Left) | Modifier |
| ⌘ Left Meta (Win / Cmd) | "Meta" | "MetaLeft" | 91 | 1 (Left) | Modifier |
| Key A | "a" / "A" | "KeyA" | 65 | 0 (Standard) | Alphanumeric |
JavaScript Keyboard Event Listener Code Examples
Practical implementation patterns for modern web user interfaces and keyboard accessibility.
1. Search Modal Shortcut (Ctrl + K / Cmd + K)
Triggers quick command palette search dialog when pressing Ctrl or Cmd with key K:
window.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
openSearchModal();
}
}); 2. Dismiss Modals with Escape Key
Improves WCAG 2.1 keyboard accessibility by closing active dialogs upon pressing Escape:
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && isModalOpen) {
closeActiveModal();
}
}); 3. Dropdown List Arrow Navigation
Controls item focus in autocomplete search dropdown lists:
listElement.addEventListener('keydown', (e) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
focusNextItem();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
focusPrevItem();
}
}); Keyboard Event Handling: Native JS vs React SyntheticEvent
In React applications, event handlers such as onKeyDown and onKeyUp do not receive the raw browser KeyboardEvent directly, but rather a SyntheticEvent (React.KeyboardEvent) instance wrapping event.nativeEvent to guarantee consistent properties across all browsers.
Use onKeyDown to intercept physical/specific keys (such as Enter, Escape, or Tab) before DOM mutations occur.
Use onChange to capture altered input text values (e.g., from autocomplete, mobile IMEs, or paste operations).
// React TypeScript Keyboard Handler
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// ✅ Using self-describing semantic strings
if (e.key === 'Enter') {
e.preventDefault();
handleSubmit(e.currentTarget.value);
} else if (e.key === 'Escape') {
closeSuggestions();
}
// Access underlying raw browser event if needed:
// const rawNativeEvent = e.nativeEvent;
}; Frequently Asked Questions (FAQ)
Technical answers regarding JavaScript keyboard events and modern browser standards.
Why are event.keyCode and event.which deprecated in modern browsers?
The W3C formally deprecated event.keyCode and event.which due to numeric inconsistencies across operating systems (Windows vs macOS vs Linux) and international layouts. Furthermore, on smartphone virtual keyboards (Android/iOS), keyCode frequently defaults to generic code 229. Developers are strongly urged to migrate to event.key and event.code.
When should I use event.key vs event.code?
Use event.key for almost all UI interactions: submitting forms via Enter, closing dialogs via Escape, and validating text input. Use event.code when you require consistent physical hardware key positioning regardless of keyboard language, such as WASD game navigation controls.
What is the difference between keydown, keypress, and keyup?
keydown triggers instantly when a key is pressed down and repeats if the key is held (event.repeat = true). keyup fires when the key is released. keypress is a legacy event that only detected printable character keys and is now obsolete.
How do you distinguish Numpad Enter from the Main Enter key?
Although both keys share event.key === "Enter", you can differentiate them via event.code === "NumpadEnter" and event.location === 3. The main Enter key has event.code === "Enter" and event.location === 0.
Why do Spacebar or Arrow keys scroll web pages downward?
Browsers have default scrolling actions tied to Space, PageDown, and Arrow keys. You can cancel this behavior by invoking event.preventDefault() within your event listener callback.
Does this tool transmit my keystrokes to a remote server?
No. 100% of the keyboard event detection, modifier calculation, and table search filtering occurs locally within your browser (client-side JavaScript). No keystroke data is ever transmitted to InfoKoding servers.