CKTIS / JavaScript
KeyboardEvent.code — physical key rather than character
KeyboardEvent.code identifies a key's physical position independently of keyboard layout and modifiers. Learn how code differs from key and where text input and virtual keyboards require a different approach.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
event.codeKeyboardEvent.code is a read-only property returning a physical key identifier as a string. Read it through event.code, for example in a keydown or keyup handler. It belongs to the UI Events Web API, not ECMAScript itself.
Names such as KeyQ, Digit2, and ShiftLeft describe key positions, not typed characters. KeyQ identifies the US-layout Q position even when another layout assigns a different letter to it. ShiftLeft and ShiftRight distinguish the keyboard's sides.
Unlike code, key describes the key's meaning with layout and modifiers taken into account. Choose code for position-based controls and key for key meaning. To observe text editing, use input rather than reconstructing text from key codes.
The default code value is "". Virtual keyboards do not always have an unambiguous physical-position equivalent. Test target browsers and devices; the presence of Node 24 does not establish support for this browser API.
The example explicitly sets code and key in synthetic events. It shows two different meanings with the same code; it does not test real keyboard mapping or simulate a physical key press.
Examples
const events = [
new KeyboardEvent("keydown", { code: "KeyQ", key: "q" }),
new KeyboardEvent("keydown", { code: "KeyQ", key: "Q", shiftKey: true })
];
for (const event of events) {
console.log(`${event.code} | ${event.key} | ${event.shiftKey}`);
}Result
KeyQ | q | false KeyQ | Q | true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.