With local & session storage, web applications can store data locally within the user's browser. Unlike cookies, local storage is more secure, and large amount of data can be stored locally without affecting the website performance. Local Storage can store data with no expiration date, data can be stored for weeks, months, years, millennium π.
Note that all this data will be stored on the user's web browser, and once the user clears all cache and cookies, the data is gone.
An alternative to local storage is session storage, Session storage stores data on the browser for only one session, i.e once the browser tab is closed, the data is gone π§.
Getting Started:
Before using local storage, you should check for browser support with the code below.
Checking for browser support:
if (typeof(Storage) !== "undefined") {
// Code for localStorage//sessionStorage
console.log("Local storage supported π")
} else {
console.log("This browser does not support local storage π€");
}
Storing && Retrieving Data:
Syntax:
##### Store Data:
localStorage.setItem("dataName", "value");
##### Retrieve Data:
localStorage.getItem("dataName");
Example:
localStorage.setItem("fullName","Asaolu Elijah π");
const me = localStorage.getItem("fullName");
console.log("My name is " + me);
//Output: My name is Asaolu Elijah π
/*This data will be stored forever in the browser unless you remove it
or the user clears all cookies and cache π€ */
Example explained:
//setItem
Dear localStorage, set an item named fullName and assign the value Asaolu Elijah to it. π
//getItem
Dear localStorage, remember the item fullName with value Asaolu Elijahπ€, assign it to another constant variable named me. ....
Another approach:
Syntax:
Store data:
localStorage.dataName = "Some Data";
Retrieve data:
var myVar = localstorage.dataname;
//Output: Some Data
Example:
localStorage.fullName = "Asaolu Elijah";
const me = localStorage.fullName;
console.log("My name is " + me);
//Output: My name is Asaolu Elijah
//This method is quite easier π€
How about session storage?
The syntax for session storage is same as that of local storage, just replace localStorage with sessionStorage and that's it π.
Example
sessionStorage.favPl = "JavaScript π";
const π©βπ» = localStorage.favPl;
console.log("My favorite programming language is " + π©βπ»);
//Output: My favorite programming language is JavaScript π
Examples of data that can be stored with local storage:
- User personal information
- Name
- ...
- Json data {}
- Literally every other stuff.
Thanks for reading, don't forget to [π, π, π, π¦,...]
I share amazing stuffs also on Twitter, click here to follow me.