[javascript] How to check whether a Storage item is set?

How can I check if an item is set in localStorage? Currently I am using

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

This question is related to javascript html local-storage

The answer is


How can one test existence of an item in localStorage? this method works in internet explorer.

<script>
    try{
        localStorage.getItem("username");
    }catch(e){
        alert("we are in catch "+e.print);
    }
</script>

The shortest way is to use default value, if key is not in storage:

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */

easist way is

if(localStorage.test){
console.log("now defined");
}
else{
console.log("undefined");
localStorage.test="defined;"
}

How it works

when you call localStorage.test first time it does not contain any store into localStorage object so it returns undefined else condition triggers. after else triggered i set new variable and again check it contains data so it return data with true in if condition


For TRUE

localStorage.infiniteScrollEnabled = 1;

FOR FALSE

localStorage.removeItem("infiniteScrollEnabled")

CHECK EXISTANCE

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}

if(!localStorage.hash) localStorage.hash = "thinkdj";

Or

var secret =  localStorage.hash || 42;

You can also try this if you want to check for undefined:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem is a method which returns null if value is not found.


localStorage['root2']=null;

localStorage.getItem("root2") === null //false

Maybe better to do a scan of the plan ?

localStorage['root1']=187;
187
'root1' in localStorage
true

You should check for the type of the item in the localStorage

if(localStorage.token !== null) {
   // this will only work if the token is set in the localStorage
}

if(typeof localStorage.token !== 'undefined') {
  // do something with token
}

if(typeof localStorage.token === 'undefined') {
  // token doesn't exist in the localStorage, maybe set it?
}

Try this code

if (localStorage.getItem("infiniteScrollEnabled") === null) {

} else {

}

You can use hasOwnProperty method to check this

> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false

Works in current versions of Chrome(Mac), Firefox(Mac) and Safari.


I've used in my project and works perfectly for me

var returnObjName= JSON.parse(localStorage.getItem('ObjName'));
if(returnObjName && Object.keys(returnObjName).length > 0){
   //Exist data in local storage
}else{
  //Non Exist data block
}

Best and Safest way i can suggest is this,

if(Object.prototype.hasOwnProperty.call(localStorage, 'infiniteScrollEnabled')){
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

This passes through ESLint's no-prototype-builtins rule.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to local-storage

Angular 6: saving data to local storage Is it safe to store a JWT in localStorage with ReactJS? How to save to local storage using Flutter? Setting and getting localStorage with jQuery Local storage in Angular 2 How to store token in Local or Session Storage in Angular 2? QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota What is the difference between localStorage, sessionStorage, session and cookies? How to save an image to localStorage and display it on the next page? Can local storage ever be considered secure?