Skip to main content

length Property – How to Get Total Items in Web Storage

The length property returns the number of properties in the specified web storage.

Syntax of the length Property

Here is length's syntax:

webStorageObject.length;

webStorageObject represents the storage object whose length you wish to verify—that is, localStorage or sessionStorage.

Examples

Below are examples of the length property.

How to verify the number of items in session storage

Invoke sessionStorage's length property.

// Store carColor: "Pink" inside the session storage:
sessionStorage.setItem("carColor", "Pink");

// Store pcColor: "Yellow" inside the session storage:
sessionStorage.setItem("pcColor", "Yellow");

// Store laptopColor: "White" inside the session storage:
sessionStorage.setItem("laptopColor", "White");

// Verify the number of items in the session storage:
sessionStorage.length;

// The invocation above may return: 3

Try Editing It

Note that your sessionStorage.length invocation may return a value greater than 3 if your browser's session storage already contains some stored information.

How to verify the number of items in local storage

Invoke localStorage's length property.

// Store carColor: "Pink" inside the local storage:
localStorage.setItem("carColor", "Pink");

// Store pcColor: "Yellow" inside the local storage:
localStorage.setItem("pcColor", "Yellow");

// Store laptopColor: "White" inside the local storage:
localStorage.setItem("laptopColor", "White");

// Verify the number of items in the local storage:
localStorage.length;

// The invocation above may return: 3

Try Editing It

Note that your localStorage.length invocation may return a value greater than 3 if your browser's local storage already contains some stored information.

Overview

This article discussed what web storage's length property 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