Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

KeyboardEvent: key value and Shift state

`key` tells you the key value, while `shiftKey` tells you whether Shift was active when the event occurred. Use both to distinguish Enter from Shift+Enter.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

event.key      // string, read-only
 event.shiftKey // boolean, read-only

KeyboardEvent.key/shiftKey refers to two read-only properties on a KeyboardEvent instance. event.key is a string: it gives the text representation of a printable key or a predefined value such as "Enter" for a special key. In browser-generated events, keyboard layout and active modifiers affect key. Use event.code instead when the physical key position matters.

event.shiftKey is a boolean: true if Shift was active when the event occurred, otherwise false. It describes that event, not the keyboard's current state. Do not confuse event.key === "Shift", which identifies the Shift key itself, with event.shiftKey, which can be true for another key.

In a keydown handler, event.key === "Enter" && event.shiftKey matches Enter with Shift active. It does not rule out other modifiers. KeyboardEvent is a Web API, not part of ECMAScript 2024; availability depends on the runtime.

Examples

{
  const eventInits = [
    { key: "Enter" },
    { key: "Enter", shiftKey: true },
  ];

  // Without KeyboardEvent, use plain objects to model just these two properties.
  const events = eventInits.map((init) =>
    typeof KeyboardEvent === "function"
      ? new KeyboardEvent("keydown", init)
      : { key: init.key, shiftKey: init.shiftKey ?? false }
  );

  for (const event of events) {
    const isShiftEnter = event.key === "Enter" && event.shiftKey;
    console.log(`${event.key} | shiftKey=${event.shiftKey} | match=${isShiftEnter}`);
  }
}

Result

Enter | shiftKey=false | match=false
Enter | shiftKey=true | match=true

Run the snippet in a browser developer console or as a script in Node.js. In a browser, it creates two synthetic `KeyboardEvent` instances without dispatching them. If the constructor is unavailable, it uses plain objects that model only `key` and `shiftKey`. Both objects have `key` set to `"Enter"`. The first omits `shiftKey` in the options, so it gets `false`; the second sets it to `true`. Only the second object matches.

Related lessons

  • JavaScript · Lesson 40 · Intermediate · Version: 3

Sources