The localStorage object stores data indefinitely without an expiration date. Data persists even after the browser is closed and remains accessible in the future, whether it’s the next day, week, or year.
// Store localStorage.setItem(“lastname”, “Smith”); // Retrieve document.getElementById(“result”).innerHTML = localStorage.getItem(“lastname”); |
Here’s the example explained:
The example above can alternatively be written as:
// Store localStorage.lastname = “Smith”; // Retrieve document.getElementById(“result”).innerHTML = localStorage.lastname; |
Here’s the syntax for removing the “lastname” localStorage item:
localStorage.removeItem(“lastname”); |
Note: Name/value pairs in localStorage are always stored as strings. Remember to convert them to another format when necessary!
The following example demonstrates counting the number of times a user has clicked a button. In this code, the string value is converted to a number to increment the counter:
if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount) + 1; } else { localStorage.clickcount = 1; } document.getElementById(“result”).innerHTML = “You have clicked the button “ + localStorage.clickcount + ” time(s).”; |
The sessionStorage object functions similarly to the localStorage object, but it stores data only for the duration of one session. Data stored in sessionStorage is deleted when the user closes the specific browser tab.
Here’s an example that counts the number of times a user has clicked a button in the current session:
if (sessionStorage.clickcount) { sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1; } else { sessionStorage.clickcount = 1; } document.getElementById(“result”).innerHTML = “You have clicked the button “ + sessionStorage.clickcount + ” time(s) in this session.”; |