LocalStorage in JavaScript

LocalStorage in JavaScript

Introduction of LocalStorage

Hello Everyone, in this article, I am going to explain what LocalStorage is in a browser and how we can access it using JavaScript. Before diving deep into LocalStorage, let's understand one important concept: the Web Storage API.

The Web Storage API is a mechanism through which we can store data locally in the user's browser. It has two components: localStorage and sessionStorage.

Both localStorage and sessionStorage save data and work in a similar way, but there is one major difference between them. With sessionStorage, the data is only accessible within the same tab or window. This means that if we close the tab or window, all the stored data vanishes. In contrast, data stored in localStorage remains accessible even after closing the tab or window.

So without any delay lets go deep down in the LocalStorage

LocalStorage enables you to store data in the form of key-value pairs, without an expiry date, ensuring accessibility throughout the browser session. It can typically hold up to 5MB of data. However, it's important to note that LocalStorage operations are synchronous, meaning they block the main thread until completion, whether reading or writing data.

Now let's move on the working of LocalStorage using JavaScript operations but before that let see what are the operation the LocalStorege do

  • To store data we use setItem()

  • To retrive data we use getItem()

  • To delete data we use removeItem()

  • To clear all the data we use clear()

setItem():

Here we want to store the username as Shivam Kumar Gupta where key is username and value is Shivam Kumar Gupta

localStorage.setItem('username', 'Shivam Kumar Gupta')

Now we can see in Local storage this data get save

LocalStorage exclusively stores data in the form of strings. Therefore, when storing data of other types, such as objects or numbers, they must be converted to strings first. Let's illustrate this with an example: suppose we need to store the names of employees along with their respective salaries

// Define sample employee data
var employees = [
    { name: "Ramesh", salary: 50000 },
    { name: "Suresh", salary: 60000 },
];


var jsonString = JSON.stringify(employees);


localStorage.setItem('employeeData', jsonString);

In the code above, we initially create an object to store the names and salaries of the employees. Then, we convert this object into a string before storing it in localStorage

getItem():

Now that we've covered storing data items in localStorage, let's move on to the next step: accessing the data we've stored.

To retrieve the stored data items from localStorage, we utilize the getItem() method. This method accepts a single parameter, which is the key associated with the value we wish to retrieve. It then returns the corresponding value


const getItem = localStorage.getItem('username')
console.log(getItem)

Now, let's explore how we can retrieve the names and salaries of the employees we previously saved in localStorage. Typically, the getItem method returns a string. However, when dealing with objects, we must convert this string back into an object using JSON.parse().


var storedData = localStorage.getItem('employeeData');

var retrievedData = JSON.parse(storedData);

console.log(retrievedData);

removeItem():

We can use the removeItem() method to delete specific data from localStorage. Simply by passing the key as a parameter to removeItem(), it removes the value associated with it.

localStorage.setItem('username1', 'Shivam Kumar Gupta')
localStorage.setItem('username2', 'Rohan Kumar Gupta')
var username = localStorage.getItem('username1');
var username = localStorage.getItem('username2');

// Removing data
localStorage.removeItem('username1');

clear():

To delete all items in localStorage we can use clear() method which will remove all the data items

locaStorage.clear()

Thanks for reading blog (^_^)

Did you find this article valuable?

Support Shivam's Blog❤️❤️ by becoming a sponsor. Any amount is appreciated!