What is local storage?

Local storage is a way to store data on the client side, even when the browser is closed. It is different from session storage, which stores data for the current session only.

Local storage is often used to store user preferences, such as language settings or login information. It can also be used to store data for web applications, such as game progress or shopping cart items.

How to use local storage in JavaScript

There are two main ways to use local storage in JavaScript:

  1. Using the localStorage object

The localStorage object is a global object that provides access to local storage data. To use the localStorage object, you first need to get a reference to it:

// Set a value in local storage
localStorage.setItem("key", "value");

const value = localStorage.getItem("key");

// Remove a value from local storage
localStorage.removeItem("key");

Usage

  • If you need a variable or important data throughout multiple files
  • If you need to store data on the client side
  • If you need to store data that is not sensitive

Example: I used it to store a stock that the user selected so that when they loaded a new page, the stock would still be there.