in JavaScript Technology

How to Add localStorage Using JavaScript?

What is localStorage in JavaScript?

localStorage allows JavaScript sites and apps to keep key-value pairs in a web browser without any expiration date. Which means the data is going to be stored in the browser even after the browser window is closed.

localStorage has at least 5MB of data storage across all major web browsers.

Read also about Double Arraylist Java

How to add local storage to JavaScript?

To add some data to local storage you need to:

localStorage.setItem("fruit", "apple");

If you want to retrieve data from local storage you need to:

const fruit = localStorage.getItem("fruit");
console.log(fruit); //prints 'apple';

Local storage only stores strings so if you want to store other types of data you need to convert it to JSON before:

localStorage.setItem("cart", JSON.stringify(["apple", "banana"]));

And to retrieve it you need to convert it from JSON:

const cart = JSON.parse(localStorage.getItem("cart"));
console.log(cart) //prints ['apple', 'banana']

Find this. is in stackoverflow discussion.

How localStorage works in general?

There are five ways to use localStorage in web applications:

  1. setItem(): Adds key and value
  2. getItem(): Gets items from localStorage
  3. removeItem(): Removes an item by key
  4. clear(): Clears all
  5. key(): Passes a number to retrieve the key

Are there any limitations in localStorage?

Yes, there are some limitations. It may sound that it is easy to implement but it is also easy to misuse it. Things that you shouldn’t use in localStorage:

  • Never store any sensitive user information in localStorage
  • There is a limit of 5MB in localStorage
  • There is no data protection in localStorage
  • localStorage can be accessed by any code on web page
  • localStorage is synchronous