Skip to content
Announcing the new Pro Zone. Check it out!

key() Storage Method – How to Get a Key from Web Storage

The key() method retrieves a web storage item’s name (key).

Syntax of the key() Method

key() accepts one required argument. Here is the syntax:

webStorageObject.key(index);
  • webStorageObject represents the storage object whose key you wish to get—that is, localStorage or sessionStorage.
  • index is the only argument accepted by key(). It is a required integer argument specifying the index of the item whose key you wish to get.

Examples

Below are examples of the key() method.

How to get the name of an item in session storage

  1. Invoke sessionStorage’s key() method.
  2. Provide the index of the item whose name you wish to get.
// Store carColor: "Pink" in the session storage:
sessionStorage.setItem("carColor", "Pink");
// Store pcColor: "Yellow" in the session storage:
sessionStorage.setItem("pcColor", "Yellow");
// Store laptopColor: "White" in the session storage:
sessionStorage.setItem("laptopColor", "White");
// Get the name of the item at index 1:
sessionStorage.key(1);

Try Editing It

How to get the name of an item in local storage

  1. Invoke localStorage’s key() method.
  2. Provide the index of the item whose name you wish to get.
// Store carColor: "Pink" in the local storage:
localStorage.setItem("carColor", "Pink");
// Store pcColor: "Yellow" in the local storage:
localStorage.setItem("pcColor", "Yellow");
// Store laptopColor: "White" in the local storage:
localStorage.setItem("laptopColor", "White");
// Get the name of the item at index 1:
localStorage.key(1);

Try Editing It