Learn about LocalStorage in JavaScript.

Javascript Jeep🚙💨
2 min readMay 29, 2023
Photo by JOSHUA COLEMAN on Unsplash

What is localStorage?

localStorage is a web storage API that allows JavaScript code to store data in the user’s browser. The data is stored in key-value pairs, and it is not deleted when the browser is closed. This makes localStorage a good choice for storing data that needs to be persisted between page loads, such as user preferences or shopping cart contents.

How to use localStorage

To use localStorage, you first need to get a reference to the localStorage object. You can do this using the window.localStorage property.

Set data to localStorage

Once you have a reference to the localStorage object, you can use the setItem() method to store data. The setItem() method takes two arguments: the key and the value. The key is a string that identifies the data, and the value is the data itself. For example, the following code would store the value “12345” in the key “myNumber”:

window.localStorage.setItem(“myNumber”, “12345”);

Get data from localStorage

To retrieve data from localStorage, you can use the getItem() method. The getItem() method takes one argument: the key. The method returns the value associated with the key, or null if the key does not exist. For example, the following code would get the value of the key “myNumber”:

var myNumber = window.localStorage.getItem(“myNumber”);

Remove data from localStorage

You can also use the removeItem() method to delete data from localStorage. The removeItem() method takes one argument: the key. For example, the following code would delete the key “myNumber”:

window.localStorage.removeItem(“myNumber”);

Limitations of localStorage

localStorage has a few limitations that you should be aware of.

  • The total amount of data that can be stored in localStorage is limited to 5MB.
  • localStorage is not secure. The data that is stored in localStorage can be accessed by any JavaScript code that is running on the page.
  • localStorage is not persistent across different browsers. If a user uses a different browser to visit your website, the data that is stored in localStorage in one browser will not be available in the other browser.

When to use localStorage

localStorage is a good choice for storing data that needs to be persisted between page loads, but it is not a good choice for storing sensitive data. If you need to store sensitive data, you should use a more secure storage mechanism, such as a database.

Here are some examples of when you might want to use localStorage:

  • Storing user preferences, such as the preferred language or the font size
  • Storing the contents of a shopping cart
  • Storing the progress of a game

Conclusion

localStorage is a powerful tool that can be used to store data in the user’s browser. However, it is important to be aware of the limitations of localStorage before you use it.

--

--