Local Storage in JavaScript
Local Storage allows JavaScript applications to store data directly inside the user's browser. The stored data remains available even after the browser is closed and opened again.
What is Local Storage?
Local Storage is a browser storage mechanism used to store data as key-value pairs.
It is commonly used for storing user preferences, application settings, theme information and other small pieces of client-side data.
Simple Definition
Local Storage is a browser feature that allows JavaScript to save data on the user's device using key-value pairs.
Local Storage stores data inside the browser using key-value pairs.
Local Storage Methods
setItem() – Stores data in Local Storage.
getItem() – Retrieves stored data.
removeItem() – Removes a specific item.
clear() – Removes all Local Storage data.
Example 1: Store and Retrieve Data
In this example, we store a username and then retrieve it from Local Storage.
localStorage.setItem("username", "Rahul");
var username = localStorage.getItem("username");
console.log(username);
Rahul
Example 2: Remove Data
The removeItem() method removes a specific value from Local Storage.
localStorage.setItem("course", "JavaScript");
localStorage.removeItem("course");
console.log("Course removed");
Course removed
Example 3: Clear Local Storage
The clear() method removes all stored Local Storage data.
localStorage.clear();
console.log("Local Storage cleared");
Local Storage cleared
Important Points
• Local Storage stores data as key-value pairs.
• Data normally remains after the browser is closed.
• Data can be accessed using JavaScript.
• Local Storage is available only on the client side.
• Do not store passwords or sensitive data in Local Storage.
Summary
Local Storage provides a simple way to store small amounts of data in the browser. The main methods are setItem(), getItem(), removeItem() and clear().