Selected topic
Web Apis
Prefer practical output? Use related tools below while reading.
Local storage is a way to store data locally on the client-side, allowing web applications to persist data even after the user closes their browser or navigates away from the page. This feature was introduced in HTML5 and provides an easy-to-use API for storing and retrieving key-value pairs.
javascript
// Add product to cart
function addToCart(product) {
const cart = localStorage.getItem('cart');
if (cart) {
const existingProducts = JSON.parse(cart);
existingProducts.push(product);
localStorage.setItem('cart', JSON.stringify(existingProducts));
} else {
localStorage.setItem('cart', JSON.stringify([product]));
}
}// Display products in cart
function displayCart() {
const cart = localStorage.getItem('cart');
if (cart) {
const products = JSON.parse(cart);
// Render the products on the page
} else {
// Handle empty cart case
}
}
localStorage.setItem(key, value): Stores a key-value pair in local storage.localStorage.getItem(key): Retrieves a value associated with a given key from local storage.localStorage.removeItem(key): Deletes the key-value pair with the specified key from local storage.localStorage.clear(): Removes all key-value pairs from local storage.