js local storage

JavaScript local storage is a way to store data in the user's browser. It is a web storage feature that allows web applications to store data locally on the user's device. This data is stored in key-value pairs, with the key being a string and the value being any type of data, including objects and arrays.

Using local storage is easy, and it can be implemented with just a few lines of code. To set an item in local storage, use the setItem() method, which takes in two parameters: the key and the value. To get an item from local storage, use the getItem() method, which takes in the key as a parameter. To delete an item from local storage, use the removeItem() method, which takes in the key as a parameter.

Here is an example of setting and getting items from local storage:


// Setting an item in local storage
localStorage.setItem('name', 'Raju');

// Getting an item from local storage
let name = localStorage.getItem('name');
console.log(name); // prints 'Raju'

For more advanced uses, you can also use the localStorage object to store more complex data, such as objects and arrays. To do this, you need to serialize the data into a string before saving it in local storage, and then deserialize it when retrieving. Here is an example of saving and retrieving an object:


// Setting an object in local storage
let user = {
  name: 'Raju',
  age: 24
};
localStorage.setItem('user', JSON.stringify(user));

// Getting an object from local storage
let userData = JSON.parse(localStorage.getItem('user'));
console.log(userData); // prints {name: 'Raju', age: 24}

Local storage is a powerful tool for web applications, as it allows developers to store data without having to rely on a server. It is important to remember, however, that local storage is not secure, and should not be used to store sensitive data. Also, keep in mind that local storage is limited in size (typically 5MB or less), and that it is cleared when the user clears their browser data.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe