What is LocalStorage & SessionStorage Objects in JavaScript ?
source link: https://www.geeksforgeeks.org/what-is-localstorage-sessionstorage-objects-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
What is LocalStorage & SessionStorage Objects in JavaScript ?
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');
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK