Skip to main content

clear() Storage Method – How to Empty Web Storage

The clear() method clears (deletes) all the items in the specified web storage.

Syntax of the clear() Method

clear() accepts no argument. Here is the syntax:

webStorageObject.clear();

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

Examples

Below are examples of the clear() method.

How to clear all items from session storage

Invoke sessionStorage's clear() method.

// 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");

// Clear all items from the session storage:
sessionStorage.clear();

// Confirm whether the session storage still contains any item:
console.log(sessionStorage);

// The invocation above will return: {length: 0}

Try Editing It

How to clear all items from local storage

Invoke localStorage's clear() method.

// 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");

// Clear all items from the local storage:
localStorage.clear();

// Confirm whether the local storage still contains any item:
console.log(localStorage);

// The invocation above will return: {length: 0}

Try Editing It

Overview

This article discussed what web storage's clear() 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