What is localstorage in JavaScript?


Summary: In this tutorial, you will learn about localstorage in JavaScript. You will learn to store and retrieve data from localstorage with the help of the examples.

localstorage in JavaScript

Local storage is a type of web storage that allows JavaScript websites and apps to store and access data right in the browser with no expiration date. This means the data stored in the browser will persist even after the browser window has been closed.

The data in local storage is stored in key-value pairs, you can store any string as a value.

You can use the localStorage object to interact with the browser’s local storage. The localStorage object provides methods for reading and writing data, such as setItem(key, value) and getItem(key).

Here’s an example of how you might use the localStorage object to store a user’s name and retrieve it later:

// Store the user's name
localStorage.setItem("username", "John");

// Retrieve the user's name
var name = localStorage.getItem("username");
console.log("Hello, " + name); // Output: "Hello, John"

Here setItem() method is used to set a key-value pair, in which the key is “username” and the value is “John” and later getItem() is used to retrieve the value by providing the key as argument.

You can also remove an item from the storage with removeItem() method and remove all items from the storage with clear() method:

// Removing an item from the storage

// Removing all items from the storage

Note: Keep in mind that the localStorage object is bound to the origin of the page, so different pages on different domains will not have access to the same storage. Also, localStorage has a storage limit, which varies between browsers and can be as low as 2.5MB.

Also, the data in localStorage is string type and if you want to store anything other than that you need to convert it using JSON.stringify() and parse with JSON.parse().

Example: Store JavaScript Object in Local Storage

Here’s an example of how you might store an object in local storage:

// Create an object to store
const user = {
  name: "John",
  age: 30,
  email: "john@example.com"

// Convert the object to a string so it can be stored in local storage
const userString = JSON.stringify(user);

// Store the object in local storage
localStorage.setItem("user", userString);

In this example, we created a simple JavaScript object containing some information about a user. We then used the JSON.stringify() method to convert the object to a string, since local storage can only store strings.

Finally, we used the localStorage.setItem() method to store the string in local storage under the key “user”.

To retrieve the object from local storage, you can use the localStorage.getItem() method and JSON.parse():

// Retrieve the object string from local storage
const storedUserString = localStorage.getItem("user");

// Convert the object string back to a JavaScript object
const storedUser = JSON.parse(storedUserString);

console.log(storedUser.name) // "John"
console.log(storedUser.age) // 30
console.log(storedUser.email) // "john@example.com"

This way, you can store the complex object with nested data and retrieve it later to use it.

It’s worth noting that storing objects in this way is vulnerable to JSON attacks and should be avoided if untrusted data can be stored and retrieved from the same keys.

When to use localstorage?

You should use local storage when you need to store small amounts of data that you want to persist even after the browser window has been closed, and that you want to be available across different pages on the same domain. Some examples of when you might use local storage include:

  • Storing user settings: You can use local storage to save the user’s preferences for your website or app, such as the color scheme or font size, so that the settings persist across different visits.
  • Storing small amounts of application state: You can use local storage to store small amounts of data that make up the current state of your app, such as a list of items in a shopping cart.
  • Caching data: You can use local storage to cache data that you have retrieved from the server, so that you don’t need to request it again the next time the user visits the page. This can improve the performance of your app.

It’s important to keep in mind that local storage is not recommended for sensitive information or large amounts of data. It’s also less secure than other storage options like cookies because it’s vulnerable to cross-site scripting (XSS) attacks, where an attacker can inject malicious code into your website and access the data in local storage.

In short, you can use local storage when you need to persist small amounts of data on the client-side that is specific to a domain, that don’t need to be sent with every request and you want to persist the data even after browser close.

Leave a Reply

Your email address will not be published. Required fields are marked *