How to Check If Local Storage Item is Set
March 28, 2020
javascript
Check if Local Storage Item is set
js
1.if (localStorage.getItem("yourItem") == null) {2.3.}
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.//
More JavaScript Snippets
Popular Articles
I Can't Believe It's Not CSS: Styling Websites with SQL
Style websites using SQL instead of CSS. Database migrations for your styles. Because CSS is the wrong kind of declarative.

How I Built an Oreo Generator with 1.1 Sextillion Combinations
Building a web app that generates 1,140,145,285,551,550,231,122 possible Oreo flavor combinations using NestJS and TypeScript.

AI Model Names Are The Worst (tier list)
A comprehensive ranking of every major AI model name, from the elegant to the unhinged. Because apparently naming things is the hardest problem in AI.