Html 5 web storage (Local storage & Session storage)πŸš€

Html 5 web storage (Local storage & Session storage)πŸš€

Β·

0 min read

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
    • Email
    • ...
  • 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.