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
Section titled “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
Section titled “Examples”Below are examples of the length property.
How to verify the number of items in session storage
Section titled “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: 3Note 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
Section titled “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: 3Note that your localStorage.length invocation may return a value greater than 3 if your browser’s local storage already contains some stored information.