Check if a Key Exists in LocalStorage using JavaScript

To check if a key exists in the browser’s local storage or not, you can use the getItem() method of the localStorage object. It’s a part of the web storage API in JavaScript.

The getItem() method returns the string value of the key if it exists in the local storage, otherwise, it returns a null value.

So, you can simply compare the value returned by the getItem() method with null.

if (localStorage.getItem('username') !== null) {
    console.log('username exists');
}
else {
    console.log('username does not exist');
}

On the other hand, if you want to set the value of a key in the browser’s local storage, you can use the setItem() method of the localStorage object.

The setItem() method takes two parameters, First, the name of the key and second, the string value of the key to be stored in the local storage of the browser.

See this example:

// Store data in local storage
localStorage.setItem('username', 'JohnDoe');
localStorage.setItem('email', 'johndoe@example.com');

// Retrieve data from local storage
const username = localStorage.getItem('username');
const email = localStorage.getItem('email');

console.log(username); // Output: JohnDoe
console.log(email); // Output: johndoe@example.com
Check if a key exists in the localstorage using JavaScript

In this example, we are storing the username and email in the local storage under the keys 'username' and 'email', respectively. The data will be available in the local storage even if the user closes the browser and opens it again.

Please note that the data stored in local storage is limited to string values. If you want to store complex data types such as objects or arrays, you need to convert them to strings using methods like JSON.stringify() before storing and JSON.parse() after retrieval.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts