LocalStorage is a client-side web storage mechanism provided by JavaScript, which allows developers to store key-value pairs directly in the user's browser. Unlike cookies, LocalStorage is persistent—data stored remains even after the browser is closed and reopened, making it ideal for retaining user preferences, session data, or any other information that needs to be accessible across page reloads.
How to Use LocalStorage in JavaScript
We will use the localStorage object in JavaScript to save user input data locally in the browser. This simple approach allows data to persist even after the user navigates away from the page or closes the browser.
- Save Data: We'll capture user input and store it locally using localStorage.setItem().
- Retrieve Data: We’ll retrieve the stored data using localStorage.getItem() and display it on the webpage.
Syntax:
// Storing data in local storage
localStorage.setItem('name', 'anyName');
// Retrieving data from local storage
const username = localStorage.getItem('name');
console.log(username); Example: Saving Data Using LocalStorage
Let’s look at a practical example where user input is saved using LocalStorage and displayed when retrieved.
<!DOCTYPE html>
<head>
<title>Example 1</title>
</head>
<body>
<div>
<h1
style="color: green;">GeeksforGeeks</h1>
<h3>Using localStorage Object</h3>
<label
for="dataInput">Enter Data:</label>
<input
type="text"
id="dataInput">
<button
onclick="saveData()">Save Data</button>
</div>
<div>
<h2>Saved Data:</h2>
<div id="savedData"></div>
</div>
<script>
function saveData() {
const data = document
.getElementById('dataInput')
.value;
localStorage
.setItem('userData', data);
displayData();
}
function displayData() {
const savedData = localStorage
.getItem('userData');
document
.getElementById('savedData')
.innerText = savedData;
}
displayData();
</script>
</body>
</html>
Output:
