How to check whether a Storage item is set?

JavascriptHtmlLocal Storage

Javascript Problem Overview


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);
}

Javascript Solutions


Solution 1 - Javascript

The getItem method in the WebStorage specification, explicitly returns null if the item does not exist:

>... If the given key does not exist in the list associated with the object then this method must return null. ...

So, you can:

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

See this related question:

Solution 2 - Javascript

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.

Solution 3 - Javascript

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 */

Solution 4 - Javascript

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

Or

var secret =  localStorage.hash || 42;

Solution 5 - Javascript

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.

Solution 6 - Javascript

there are couple of methods to check i am adding them here

Method 1

if("infiniteScrollEnabled" in localStorage){
     console.log("Item exists in localstorage");
}else{
    console.log("Item does not exist in localstoarge";
}

Method 2

if(localStorage.getItem("infiniteScrollEnabled") === null){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

Method 3

if(typeof localStorage["cart"] === "undefined"){
    console.log("Item does not exist in localstoarge";
}else{
   console.log("Item exists in localstorage");
}

Method 4

if(localStorage.hasOwnProperty("infiniteScrollEnabled")){
     console.log("Item exists in localstorage");
 }else{
    console.log("Item does not exist in localstoarge";
 }

Solution 7 - Javascript

Can try something like this:

 let x = localStorage.getItem('infiniteScrollEnabled') === null ? "not found" : localStorage.getItem('infiniteScrollEnabled')

Solution 8 - Javascript

For TRUE

localStorage.infiniteScrollEnabled = 1;

FOR FALSE

localStorage.removeItem("infiniteScrollEnabled")

CHECK EXISTANCE

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

Solution 9 - Javascript

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>

Solution 10 - Javascript

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?
}


Solution 11 - Javascript

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.

Solution 12 - Javascript

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
}

Solution 13 - Javascript

I'm late to this party, but checking localStorage for the existence of keys (or the existence of key values) is easily done with localDataStorage, a handy utility wrapper I created.

After instantiating the wrapper with something like

myLDS = localDataStorage( 'segmentedStorageHere' );

you can set keys

myLDS.set( 'infiniteScrollEnabled', true );

in a straightforward manner. Note that this example is actually passing a boolean value to the store, where it can be retrieved with

let scrollingState = myLDS.get( 'infiniteScrollEnabled' );

and scrollingState will contain the boolean value returned. The wrapper keeps track of the native JavaScript data type for you, seamlessly (Array, Boolean, Date, Number, Object, etc.) No more JSON stringifying/parsing in your code.

Now when we need to know if a key is in the store, we can check it like this

if( myLDS.haskey( 'infiniteScrollEnabled' ) ) {
    console.log( "It's been set!" ); 
} else {
    console.log( "The key is not set." ); 
}

You can also check whether a particular value is present. For example

myLDS.set( 'myNumber', 1234.5678 );
console.log( myLDS.hasval( 1234.5678 ) );    --> true



Solution 14 - Javascript

As @Christian C. Salvadó has mentioned above you can do if (xxx === null){}

but null is also a falsy value, like so:

if (null){
console.log ("hello");
}

which does not print "hello".

Solution 15 - Javascript

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

Solution 16 - Javascript

Try this code

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJiew MengView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptStephan HoyerView Answer on Stackoverflow
Solution 3 - JavascriptVladislavView Answer on Stackoverflow
Solution 4 - JavascriptDeepak ThomasView Answer on Stackoverflow
Solution 5 - JavascriptPrime_CoderView Answer on Stackoverflow
Solution 6 - JavascriptVikas KandariView Answer on Stackoverflow
Solution 7 - JavascriptAyush ChoudharyView Answer on Stackoverflow
Solution 8 - JavascriptDerinView Answer on Stackoverflow
Solution 9 - Javascriptle vantardView Answer on Stackoverflow
Solution 10 - JavascriptwebmasterView Answer on Stackoverflow
Solution 11 - JavascriptGaurav GandhiView Answer on Stackoverflow
Solution 12 - JavascriptRahul VanaveView Answer on Stackoverflow
Solution 13 - JavascriptMacView Answer on Stackoverflow
Solution 14 - JavascriptheyyyView Answer on Stackoverflow
Solution 15 - JavascriptzloctbView Answer on Stackoverflow
Solution 16 - JavascriptDaniel WichersView Answer on Stackoverflow