Use of localStorage in JavaScript with example

Last updated on : Jun 23, 2023 by Ashwini Upadhyay

In this tutorial, we will learn the use of localStorage in JavaScript with example, the localStorage object is a part of the Web Storage API, which provides a way to store key-value pairs in a web browser. The data stored using localStorage remains persistent even after the browser is closed and reopened. It is commonly used for storing user preferences, application states, or caching data.

As you can see this example illustrates the usage of localStorage in JavaScript:

// Storing data in localStorage
localStorage.setItem('username', 'Hero');
localStorage.setItem('isLoggedIn', 'true');

// Retrieving data from localStorage
const username = localStorage.getItem('Hero');
const isLoggedIn = localStorage.getItem('isLoggedIn');

console.log(username);      // Output: Hero
console.log(isLoggedIn);    // Output: true

// Updating data in localStorage
localStorage.setItem('username', 'Hero2');

// Removing data from localStorage
localStorage.removeItem('isLoggedIn');

// Clearing all data in localStorage
localStorage.clear();

In the above example, we first store two key-value pairs using the setItem() method. The keys are “username” and “is logged in,” and their corresponding values are “Hero” and “true,” respectively.

localStorage provides a set of methods to interact with the stored data:

  • setItem(key, value): We can update the value associated with a key by calling setItem() again with the same key. In the example, we change the value of the “username” key to “Hero2.
  • getItem(key): To retrieve the data, we use the getItem() method and pass the key as an argument. The retrieved values are then stored in the username and isLoggedIn variables.
  • removeItem(key): To remove a specific item, we use the removeItem() method and provide the key as an argument. In this case, we remove the “is logged in” key-value pair.
  • clear(): If we want to clear all the data stored, we can call the clear() method.
  • key(index): Retrieves the key at a specific index in the storage.

It’s important to note that the data stored localStorage is limited to the specific domain and protocol of the website. Each domain has its own isolated storage, and JavaScript code from one domain cannot access the storage of another domain for security reasons.

Also, data stored in localStorage is stored as strings. If you need to store complex data types, such as objects or arrays, you must convert them to strings using JSON.stringify() before storing them and using JSON.parse() them when retrieving them. have to be parsed back into their original form.

As you can see in this example usage of JSON.stringify() and JSON.parse() in localStorage.

// Storing and retrieving complex data types
const data = {
  name: 'Hero',
  age: 25,
  hobbies: ['reading', 'gaming', 'traveling']
};

localStorage.setItem('data', JSON.stringify(data));

const storedData = JSON.parse(localStorage.getItem('data'));

console.log(storedData);
// Output: { name: 'Hero', age: 25, hobbies: ['reading', 'gaming', 'traveling'] }

In this example, we use JSON.stringify() to convert the data object into a string before storing it in localStorage. When retrieving the data, we parse the string using JSON.parse() to convert it back into an object.

ashwini upadhyay

Ashwini Upadhyay

I'm a full-stack developer, owner of LogicalDuniya.I love to write tutorials and tips that can help to other artisan. I love to write on PHP, Laravel, Angular, Vue, React, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

Recommended Posts :


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Press ESC to close