localStorage is a window property that allows you store data locally within the website origin. The data save in localStorage will still be available even after you close the browser, or even if you come back tomorrow, or next week, or even next year.

How to access localStorage?

Here are some ways to access localStorage:

Access directly from the window object.
const storage = window.localStorage();
Store localStorage to a variable.

What are the localStorage methods?

  1. setItem() - Add a key-value pair data
  2. getItem() - Retrieve a data by key
  3. removeItem() - Remove an item by key
  4. clear(): Clear all data from localStorage

setItem(key, value)

Add a key-value pair data. The first argument is the key or the unique identifier for the value. The send argument is the a String. If you want to store and Object to localStorage, you must stringify it first.

Store a String

window.localStorage.setItem('hello', 'world');

Storge an Object

// The Object we want to store
const greeting = {
  greeting: 'Hello World!'

// The stringified version of the Object using JSON.stringify.
const stringified = JSON.stringify(greeting);

// Set the data to localStorage
window.localStorage.setItem('greeting', stringified);


The argument is the key or unique identifier for the data stored in localStorage. Let's retrieve the Object we stored from the first example.

// The string version of the Object.
const stringified = window.localStorage.getItem('greeting');

// We are converting the the stringified value
// back to its Object form.
const greeting = JSON.parse(stringified);

 * {
 *   greeting: 'Hello World!'
 * }


Remove a single item by key or unique identifier from localStorage



This method will delete all data in the localStorage.



Take note the the data in the localStorage is only present per origin meaning, the localStorage data in www.website1.com is not present in www.website2.com.