Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Local Storage

localStorage is a type of client-side storage provided by modern browsers. It allows web applications to store data locally on a user's device, offering persistent storage even after the browser is closed and reopened. It stores the data in key-value pairs where key is the string to indentify the data and the value is the actual data itself stored as a string.

Examples

Storing Data:

localStorage.setItem('key', 'value');

This stores a key-value pair ('key' as the key and 'value' as the corresponding value) in the localStorage of the browser. This data will persist even after the browser is closed and reopened.

Retrieving Data

const data = localStorage.getItem('key');

It will retrieve the value associated with the key 'key' from the localStorage and stores it in the variable 'data'. It allows you to access previously stored data from localStorage.

Removing Data:

localStorage.removeItem('key');

It will remove the key-value pair with the key 'key' from the localStorage. After execution, the data associated with the specified key will no longer be available in the localStorage.

Clearing All Data:

localStorage.clear();

It will clear all the data stored in the localStorage of the browser. It removes all key-value pairs, effectively resetting the localStorage to an empty state.

Storing Complex Data

const user = {
    name: 'John Doe',
    age: 25
}
localStorage.setItem('user', JSON.stringify(user));

To store complex data such as objects or arrays in localStorage, you first need to convert the data into a string using JSON.stringify() method. This ensures that the data is stored in a format that can be easily retrieved and parsed later.

Retrieving Complex Data

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

This code retrieves the complex data stored in localStorage under the key 'user' and parses it back into a JavaScript object. Now, the variable userData contains the user object with properties like name and age.

Use Cases

localStorage provides several advantages and can be used in various scenarios with web applications:

  • Storing user preferences and settings like language, theme choices.
  • Caching frequently used data to improve performance.
  • Implementing "Remember Me" functionality in login systems.
  • Storing application state for seamless user experience.
  • Storing offline data for progressive web applications.
  • Maintaining user login information or shopping cart contents.

Limitations

While convenient, localStorage comes with certain limitations:

  • Limited storage capacity (typically around 5MB per origin).
  • Data stored in localStorage is accessible across browser tabs/windows within the same origin, which may pose security risks if sensitive data is stored.
  • Not suitable for storing sensitive information such as passwords or authentication tokens without encryption.