Skip to main content

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

important

The user-agent defines the order of items in the session storage. In other words, key()'s output may vary based on how the user-agent orders the web storage's items. Therefore, do not rely on key() to return a constant value.

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

important

The user-agent defines the order of items in the local storage. In other words, key()'s output may vary based on how the user-agent orders the web storage's items. Therefore, do not rely on key() to return a constant value.

Overview

This article discussed what web storage's key() method is. We also used examples to see how it works.

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Tweet this article