Welcome to our comprehensive guide on the JavaScript Web Storage API! This tutorial is designed to help both beginners and intermediates understand how to store data in a browser using this powerful tool. 📝
The Web Storage API allows web applications to store data in the user's browser. Unlike cookies, which have a limited size and can only store simple data, the Web Storage API offers larger storage capacity and the ability to store complex data types. 💡
To access the storage, we use the window.localStorage or window.sessionStorage properties.
// Accessing local storage
let storage = window.localStorage;
// Accessing session storage
let session = window.sessionStorage;To store data, we use the setItem() method.
// Storing data in local storage
storage.setItem('name', 'John Doe');
// Storing data in session storage
session.setItem('score', 85);To retrieve data, we use the getItem() method.
// Retrieving data from local storage
let name = storage.getItem('name');
console.log(name); // John Doe
// Retrieving data from session storage
let score = session.getItem('score');
console.log(score); // 85To update data, we can retrieve the existing data, modify it, and then store it back using setItem().
// Retrieve data and update it
let currentScore = session.getItem('score');
currentScore++;
session.setItem('score', currentScore);To remove data, we use the removeItem() method.
// Removing data from local storage
storage.removeItem('name');
// Removing data from session storage
session.removeItem('score');To check if data exists, we can use the length property.
// Check if data exists in local storage
if (storage.length > 0) {
console.log('Data exists');
} else {
console.log('No data');
}What is the difference between local storage and session storage?
Let's create a simple to-do list application using local storage.
// Initialize an array to store tasks
let tasks = [];
// Function to add tasks
function addTask(task) {
tasks.push(task);
saveTasks();
}
// Function to save tasks in local storage
function saveTasks() {
localStorage.setItem('tasks', JSON.stringify(tasks));
}
// Function to retrieve tasks from local storage
function loadTasks() {
tasks = JSON.parse(localStorage.getItem('tasks'));
}
// Load tasks on page load
loadTasks();Now, whenever a user adds a task, we save it to local storage using the saveTasks() function. When the page loads, we load the tasks from local storage using the loadTasks() function.
This way, the user's tasks are saved and loaded even if they close the browser and reopen it later. 🚀