WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Working with localStorage in JavaScript

localStorage is a feature in web browsers that allows web applications to store key-value pairs locally within the user's browser.

localStorage can be useful for applications that need to persist data across sessions or pages.

Each browser sets a storage limit for localStorage, which typically ranges from 5MB to 10MB. Exceeding this limit can result in storage errors, so it's important to manage the data stored in localStorage with caution.

localStorage is specific to each domain. Data stored in localStorage for one domain is not accessible by other domains, ensuring data privacy and security.

Data stored in localStorage remains available even if the user navigates to different pages within the same domain. This makes it a convenient tool for maintaining state across different pages of a web application.

Here's a simple guide on how to use the localStorage methods in JavaScript:

Set an item in localStorage

To store data in localStorage, you can use the setItem method.

localStorage.setItem('name', 'Eduard');

Get an item from localStorage

To retrieve data from localStorage, use the getItem method.

var getName = localStorage.getItem('name');
console.log(getName); // Eduard

Remove an item from localStorage

To remove an item from localStorage, use the removeItem method.

localStorage.removeItem('name');
console.log(localStorage.getItem('name')); // null

Clear all items from localStorage

If you want to clear all items from localStorage, you can use the clear method.

localStorage.clear();

Handling data conversion

Remember that everything you store in localStorage is converted to strings. If you want to store objects or arrays, you'll need to convert them to strings using JSON.stringify and then parse them back using JSON.parse when retrieving them.

// Storing an object
let person = { name: 'Eduard', age: 32 };
localStorage.setItem('person', JSON.stringify(person));

// Retrieving the person object
var getPerson = JSON.parse(localStorage.getItem('person'));
console.log(getPerson); // { name: 'Eduard', age: 32 }