How to Use localStorage in JavaScript
As a developer, you are likely to face a scenario where you need to store data temporarily on the client-side of a web application. Here comes the handy localStorage feature available in JavaScript. This feature allows you to store data on the client-side browser and retrieve it whenever necessary. In this article, we will walk you through how to use localStorage in JavaScript.
LocalStorage is a simple key-value store provided by the web browser. It allows you to store data locally on the user’s browser, even if the user closes the window or reloads the page. This makes it a convenient tool for session-based applications or small web projects, where you need to keep track of user activity.
LocalStorage is simple to use, you just need to follow these three simple steps:
- Set data to LocalStorage
To set data to localStorage, you need to follow this syntax:
“`localStorage.setItem(key, value);“`
Here key and value are the two parameters. Key defines the name of the data and value is the actual value of the data that you want to store.
For example, let’s store a string “hello world” to localStorage with the key “message”:
“`javascript
localStorage.setItem(‘message’, ‘hello world’)
“`
- Get data from LocalStorage
To retrieve data from LocalStorage, you need to follow this syntax:
“`localStorage.getItem(key);“`
Here, you only need to pass the key as the parameter, which will be used to retrieve the respective value.
For example, let’s get the value of the key “message”:
“`javascript
const message = localStorage.getItem(‘message’)
console.log(message) // prints “hello world”
“`
- Remove data from LocalStorage
Removing data from LocalStorage is also very simple. You just need to follow this syntax:
“`localStorage.removeItem(key);“`
Here again, you only need to pass the key that you want to remove.
For example, let’s remove the key “message”:
“`javascript
localStorage.removeItem(‘message’)
“`
And that’s it! You have successfully removed the key “message” from LocalStorage.
LocalStorage has a few limitations that you should be aware of:
– LocalStorage is limited to 5-10 megabytes per origin (depending on the browser).
– You can only store strings in LocalStorage, which means that you need to serialize and deserialize data to store objects, arrays, and other types of data.
– LocalStorage is synchronous, which means that blocking I/O operations can have a significant impact on the performance of the application.