Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Storage.length and Storage.key(): count entries and read key names

`length` counts stored entries, and `key(index)` returns a key name by position. The browser does not guarantee the order of those positions.

Version: Current web platform; runtime support varies

Syntax

// Web Storage is defined by the HTML Living Standard, not ECMAScript 2024.
storage.length                 // number (read-only)
storage.key(index)             // string | null; zero-based index
storage.getItem(name)          // string | null; lookup by key name

Storage.length/key refers to two members of a Storage instance. The read-only property storage.length counts the key–value pairs currently stored; it does not measure bytes or quota. The method storage.key(index) returns a key name as a string, not its value. Positions start at zero: pass a nonnegative integer in the unsigned long range (0 through 2 ** 32 - 1). If the converted index is at least the current length, the method returns null.

To read the value, pass the name to storage.getItem(name). That method also returns null, but in this case it means the named key is absent. Check the result of key() with name !== null, because the empty string can be a valid key name.

Key order is implementation-defined and can change after a mutation. Do not assume insertion order or save an index as a key identifier. If display order matters, collect the names and sort them explicitly. Caching length does not create a snapshot: changes during traversal can cause keys to be skipped or visited twice.

This is the HTML Standard's Web Storage API, not a feature of ECMAScript 2024. window.localStorage is scoped to an origin and can survive browser restarts. window.sessionStorage is also separated by top-level tab or window: it survives reloads but is tied to the page session. Do not assume availability in every runtime. Getting either storage object can throw SecurityError for an opaque origin or because of browser policy, and a write can throw QuotaExceededError, for example when the quota is exhausted.

Examples

(() => {
  function demonstrate(storage) {
    if (storage.length !== 0) {
      throw new Error("Use an empty sessionStorage area.");
    }

    try {
      console.log(storage.length);
      storage.setItem("theme", "dark");
      storage.setItem("lang", "en");

      const count = storage.length;
      const names = [];
      for (let index = 0; index < count; index++) {
        const name = storage.key(index);
        if (name !== null) names.push(name);
      }

      console.log(count);
      console.log(JSON.stringify(names.sort().map(name => [name, storage.getItem(name)])));
      console.log(storage.key(count));
    } finally {
      storage.removeItem("theme");
      storage.removeItem("lang");
    }
  }

  const storage = globalThis.sessionStorage;
  if (storage !== undefined) {
    demonstrate(storage);
  } else {
    // If Node.js 24 has not exposed Web Storage, enable it in a fresh process.
    const { execFileSync } = require("node:child_process");
    execFileSync(
      process.execPath,
      ["--experimental-webstorage", "-e", `(${demonstrate.toString()})(globalThis.sessionStorage);`],
      { stdio: "inherit" },
    );
  }
})();

Result

0
2
[["lang","en"],["theme","dark"]]
null

Run this in the browser console on an HTTP(S) page in a test tab with empty `sessionStorage`, storage access allowed, and no other code changing that area. Sorting makes the output independent of browser key order. `key(count)` returns `null`, and `finally` removes only the two entries the example uses. For Node.js 24, save the snippet as `main.js` and run `node main.js`; the snippet enables built-in Web Storage in a child process if needed.

Related lessons

  • JavaScript · Lesson 42 · Advanced · Version: 4

Sources