JavaScript LocalStorage Methods with Examples

The localStorage object is a type of web storage that allows Javascript websites and apps to store and access data right in the browser with no expiration date. This means the data stored in the browser will persist even after the browser window has been closed. The localStorage property object is read-only.

JavaScript LocalStorage Methods

To use LocalStorage in your web applications, there are 5 methods to choose from:
  1. setItem(): Add key and value to LocalStorage
  2. getItem(): Retrieve a value by the key from LocalStorage
  3. removeItem(): Remove an item by key from LocalStorage
  4. clear(): Clear all LocalStorage
  5. key(): Passed a number to retrieve nth key of a LocalStorage

Syntax

window.localStorage
The syntax for SAVING data to localStorage:
localStorage.setItem("key", "value");
The syntax for READING data from localStorage:
var lastname = localStorage.getItem("key");
The syntax for REMOVING data from localStorage:
localStorage.removeItem("key");
The syntax for CLEAR all data:
localStorage.clear();
Syntax for Key() Method:
var KeyName = localStorage.key(index);
Let's demonstrate each method with an example.

localStorage Methods Examples


Comments