How to Check If Local Storage Item is Set

/

March 28, 2020

Check if Local Storage Item is set

js
1.if (localStorage.getItem("yourItem") == null) {
2.}

The getItem method on the localStorage object in HTML5 specifies that if an item does not exist then it will return null. All we have to do is check whether the method returns null or not.

Examples

js
1.if (localStorage.getItem("username") == null) {
2. console.log("Item does not exist");
3.}
4.// Item does not exist
js
1.localStorage.setItem("username", "cody");
2.
3.if (localStorage.getItem("username") == null) {
4. console.log("Item does not exist");
5.}
6.//

Function for checking local storage

We can encapsulate this in a function as follows:

js
1.const isInStorage = str => localStorage.getItem(str) !== null;

Examples

js
1.if (isInStorage("username")) {
2. console.log("Item does not exist");
3.}
4.// Item does not exist
js
1.localStorage.setItem("username", "cody");
2.
3.if (isInStorage("username")) {
4. console.log("Item does not exist");
5.}
6.//