by Sai gowtham

How to check if the localStorage key exists or not in JavaScript

In this tutorial, we are going to learn about checking a key exists or not in localStorage using JavaScript.

Using the localStorage.getItem() method

To check if a key exists or not in localStorage, we can use the localStorage.getItem() method.

The localStorage.getItem() method takes the key as an argument and returns the key’s value. if a key doesn’t exist it returns the null.

Here is an example:

const name = localStorage.getItem('name');

if(name){
    console.log('Name exists');
}else{
    console.log('Name is not found');
}

In the above example, if a name key exists in the localStorage it prints the if block statement or it prints the else block statement if a key doesn’t exist.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course