localStorage array objects in Javascript

What is HTML5 Local Storage

localStorage is a new API (Application Programming Interface) introduced in HTML5. It is used to store data from website data within the user’s browser.

localStorage and sessionStorage, part of the web storage API, are two great tools to save key/value pairs locally. If you click the save button at the top of this post, localStorage is what’s used to store your saved posts.

Both localStorage and sessionStorage offer advantages compared to using cookies:

  1. The data is saved locally only and can’t be read by the server, which eliminates the security issue that cookies present.
  2. It allows for much more data to be saved (10Mb for most browsers).
  3. It’s simpler to use and the syntax is very straightforward.
  4. It’s also supported in all modern browsers, so you can use it today without an issue. Obviously, since the data can’t be read on the server, cookies still have a use, especially when it comes to authentication.

Also Local Storage is categorized based on origins. An origin means a domain and a protocol. Data can be accessed and stored by all pages from that origin.

How to storing and retrieving objects with localStorage?

Only strings can be stored with localStorage or sessionStorage, but you can use JSON.stringify to store more complex objects and JSON.parse to read them:

let obj = { fn: 'Nandu', ln: 'Singh' };
localStorage.setItem("session", JSON.stringify(obj));

let value = JSON.parse(localStorage.getItem("session"));

Delete an entry with the removeItem method:

localStorage.removeItem(key);

If we need to delete all entries of the store we can simply do:

localStorage.clear();

#localstorage #html5 #javascript

localStorage array objects in Javascript
121.00 GEEK