localStorage, sessionStorage and Cookies in JavaScript
In JavaScript, you can use web storage to save data persistently in the browser: localStorage,sessionStorage, and cookies are the three main options.
Syntax:
These are the most common ways to store data:
- localStorage: Used for persistent data storage. `localStorage.setItem('key', 'value');`.
Example:
// Save data to localStorage localStorage.setItem('user', 'Juan'); // Retrieve the data const user = localStorage.getItem('user'); console.log(user); // Output: Juan // Remove the data localStorage.removeItem('user');
Explanation:
In this example, key-value data is stored inlocalStorage, retrieved, and then removed. Data stored here persists even if you close the browser.
- sessionStorage: Saves data only during the current page session. `sessionStorage.setItem('key', 'value');`.
Example:
// Save data to sessionStorage sessionStorage.setItem('theme', 'dark'); // Retrieve the data const theme = sessionStorage.getItem('theme'); console.log(theme); // Output: dark // Remove the data sessionStorage.removeItem('theme');
Explanation:
Here, data is stored in sessionStorage. This data is automatically deleted when you close the tab or browser.
- Cookies: Stores data in the browser that can expire. `document.cookie = 'key=value';`.
Example:
// Create a cookie with an expiration date document.cookie = 'language=es; expires=' + new Date(2025, 0, 1).toUTCString(); // Read all cookies console.log(document.cookie); // Output: language=es // Delete a cookie (set a past date) document.cookie = 'language=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
Explanation:
Cookies allow you to store data with a specific expiration date. In the example, a cookie is created that expires in 2025, then printed, and finally deleted.
Purpose:
web storage allows you to save data efficiently and retrieve it on future visits or sessions.
Exercises
Interactive Exercise 1: Drag and Drop.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Exercise 2: Fill in the Blanks
Rellena los huecos en cada casilla.
<html> <head> <title>Web Storage</title> </head> <body> <h1>Web storage demonstration</h1> <script> .setItem('key', 'value'); </script> </body> </html>
Exercise 3:
Complete the code in the editor to save and display a variable's value using web storage.
JavaScript Concepts and Reference
Functions
Objects in JavaScript
Arrays
DOM (Document Object Model)
Error Handling
Promises and Asynchronicity
Modules in JavaScript
ES6 and Advanced Features
What is the difference between LocalStorage and cookies? What is the difference between sessionStorage and localStorage? What is the advantage of JavaScript's localStorage object compared to cookies? What is sessionStorage in JavaScript? localStorage vs sessionStorage localStorage JavaScript sessionStorage JavaScript localStorage vs cookies localStorage getItem localStorage vs sessionStorage vs cookies localStorage React localStorage is not defined