Have you ever wondered how websites remember your choices after you close the browser? That’s Local Storage at work.
What is Local Storage?
Local Storage is a browser feature that lets developers store small data amounts on users’ devices. This data stays even after the browser is closed, like digital notes for websites.
Why Local Storage?
Unlike remote servers, Local Storage is perfect for quick access to user data like preferences. Most modern browsers support it, ensuring compatibility.
In this tutorial, I show how you can use Local storage in your project using JavaScript.
Table of Content
- Getting Started with Local Storage
- Updating and Deleting Local Storage Data
- Clearing Local Storage
- Working with Objects and Arrays
- Handling Errors
- Example of Using Local Storage in JavaScript
- Conclusion
1. Getting Started with Local Storage
The Web Storage API has two primary methods of local data storage: Local Storage and Session Storage. Our emphasis in this guide will be on Local Storage. It’s crucial to recognize that unlike Session Storage, which is confined to the ongoing browser session, Local Storage remains intact even after the browser is closed.
Storing Data
Use the following syntax to store data in Local storage –
localStorage.setItem(key, value);
Here, the key
is like a label, and the value
is the actual data you want to store.
Example:
localStorage.setItem('name', 'Yogesh singh');
Retrieving Data
Use the following syntax to read stored data from the Local storage –
localStorage.getItem(key);
Provide the key
which you want to read, and you’ll get the associated value.
const name = localStorage.getItem('name'); console.log(name); // Output: Yogesh singh
Remember, though, that Local Storage only stores strings. If you need to store more complex data types like objects or arrays, we’ll explore how to handle that shortly.
2. Updating and Deleting Local Storage Data
Updating Data
Updating Local storage data is the same as storing data. Use the same setItme()
method to update an existing value.
Example –
localStorage.setItem('name', 'Sonarika Bhadoria');
Here, I updated the name
key value.
Deleting Data
Removing data from Local Storage is equally straightforward. You can use the localStorage.removeItem(key)
method and pass the key of the data you want to remove.
localStorage.removeItem('name');
Here, deleting name
key.
3. Clearing Local Storage
To delete all Local storage data, use the clear()
method. It has the following syntax:
localStorage.clear();
This method removes all key-value pairs, effectively resetting Local Storage.
Keep in mind that clearing Local Storage is a drastic action. Only use it when you have a valid reason, such as performing a cleanup or resetting user preferences.
4. Working with Objects and Arrays
In Local Storage you can also store Arrays and Objects.
Storing Objects and Arrays
Local Storage is designed to hold data in string format. It is required to first convert it into a string using JSON.stringify()
.
const userInfoObject = { name: 'Yogesh singh', city: 'Bhopal', age: 30, }; localStorage.setItem('userinfo', JSON.stringify(userInfoObject));
Here, I stored a userInfoObject
Object stored in Local storage in userinfo
key. Similarly, you can do this with an Array.
Retrieving Objects and Arrays
To revert the stored value to the original form use JSON.parse()
after reading the data using getItem()
.
const userData = JSON.parse(localStorage.getItem('userinfo')); console.log(userData.name); // Output: Yogesh singh
5. Handling Errors
In JavaScript, you can easily handle errors using a try-catch block. It is good practice to wrap Local storage code in a try-catch
block to catch any errors that might arise. By using this you can ensure that even if something goes wrong, your application won’t crash completely. Instead, it will display an error message and continue running.
try { localStorage.setItem('name', 'Yogesh singh'); } catch (error) { console.error('An error occurred:', error); }
6. Example of Using Local Storage in JavaScript
Below is a straightforward illustration of how Local Storage works.
Three text elements and two buttons have been set up, each with a defined click event.
In the JavaScript code, three functions have been created:
- loadData(): This function retrieves stored Local Storage data and displays it within the text elements.
- saveData(): Upon clicking the submit button, data is saved to Local Storage.
- deleteData(): When the delete button is clicked, the associated Local Storage data is removed.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> Name : <input type="text" id="name"> <br><br> City : <input type="text" id="city"> <br><br> Age : <input type="text" id="age"> <br><br> <input type="button" id="btnsave" value="Submit" onclick="saveData();"> <input type="button" id="btndelete" value="Delete" onclick="deleteData();"> <!-- Script --> <script type="text/javascript"> // Display stored Local storage data on page load loadData(); function loadData(){ try{ if(localStorage.getItem('userinfo')){ const userinfo = JSON.parse(localStorage.getItem('userinfo')); document.getElementById('name').value = userinfo.name; document.getElementById('city').value = userinfo.city; document.getElementById('age').value = userinfo.age; } }catch (error) { console.error('An error occurred:', error); } } // Save data to Local storage function saveData(){ const name = document.getElementById('name').value; const city = document.getElementById('city').value; const age = document.getElementById('age').value; try{ const userInfoObject = { name: name, city: city, age: age }; localStorage.setItem('userinfo', JSON.stringify(userInfoObject)); }catch (error) { console.error('An error occurred:', error); } } // Delete Data function deleteData(){ try{ localStorage.removeItem('userinfo'); alert('Data cleared successfully.'); }catch (error) { console.error('An error occurred:', error); } } </script> </body> </html>
Output:
7. Conclusion
Utilizing Local Storage is straightforward, involving only a handful of uncomplicated procedures to store and retrieve information. Its stored data remains accessible even after closing the browser.
Each domain possesses a finite storage capacity, typically ranging from 5 to 10 MB. However, it’s essential to remember that sensitive information should not be stored in Local Storage.
Accessing stored Local Storage data is conveniently achievable via the browser’s Application Tab. This feature allows effortless observation and potential modification of the established Local Storage variables.
If you found this tutorial helpful then don't forget to share.