What is LocalStorage & SessionStorage Objects in JavaScript ?
Last Updated :
02 Feb, 2024
LocalStorage
and sessionStorage
are Web Storage API objects in JavaScript for key-value data storage. localStorage
persists data across browser sessions, while sessionStorage
is limited to the current session, clearing on browser/tab closure. Both are associated with the origin and provide simple ways to store and retrieve data.
Some methods are used to deal with local and session storage:
- setItem(): This function is used to set the field and its respective value in the browser storage.
- getItem(): This function is used to get or fetch the value of the field that was stored initially in the browser storage.
- removeItem(): This function is used to delete or remove the field and its respective value from the storage permanently.
Example for setting the localStorage in the browser:
// Storing data in local storage
localStorage.setItem('name', 'anyName');
// Retrieving data from local storage
const username = localStorage.getItem('name');
console.log(username); // Output: anyName
// Removing data from local storage
localStorage.removeItem('name');
Example for setting the sessionStorage in the browser:
// Storing data in session storage
sessionStorage.setItem('auth', 'true');
// Retrieving data from session storage
const theme = sessionStorage.getItem('auth');
console.log(theme); // Output: true
// Removing data from session storage
sessionStorage.removeItem('auth');
Share your thoughts in the comments
Please Login to comment...