setItem VS getItem

setItem VS getItem

As a web developer, I have often come across the necessity to store data on the client-side. This data can be user preferences, session data, or any other information that needs to be persisted across different pages or sessions. In order to achieve this, there are two methods available in JavaScript - setItem() and getItem().

setItem()

setItem() is a method available in the Web Storage API that allows us to store a key-value pair in the browser's localStorage or sessionStorage. The syntax for the method is as follows:

localStorage.setItem(key, value);
sessionStorage.setItem(key, value);
  • The first parameter is the key that we want to store the value under.
  • The second parameter is the value that we want to store.

The key-value pair is stored as a string in the browser's storage. If we want to store an object, we need to first convert it to a JSON string using JSON.stringify().

getItem()

getItem() is a method available in the Web Storage API that allows us to retrieve a value stored in the browser's localStorage or sessionStorage. The syntax for the method is as follows:

localStorage.getItem(key);
sessionStorage.getItem(key);

The parameter for the method is the key for which we want to retrieve the value. The returned value is always a string. If we want to retrieve an object, we need to first parse the JSON string using JSON.parse().

Difference between setItem() and getItem()

The main difference between setItem() and getItem() is that setItem() is used to store a key-value pair in the browser's storage, while getItem() is used to retrieve a value stored using a key in the browser's storage. Another difference is that setItem() overwrites the value if the key already exists, while getItem() returns null if the key does not exist.

Both methods are extremely useful in various scenarios. We can use setItem() to store user preferences or session data and retrieve it across different pages or sessions using getItem(). These methods provide an easy and efficient way to store data on the client-side.

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