394

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);
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

17 Answers17

683

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:

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    Could you add your own method to `localStorage` to encapsulate this little test? E.g. `localStorage.hasItem("infiniteScrollEnabled")`? – Paul D. Waite Jul 17 '10 at 01:10
  • 5
    @Paul: Yes, you could even augment the `Storage.prototype` object, but as a rule of thumb I always recommend to [not modify objects you don't own](http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/), specially host objects. – Christian C. Salvadó Jul 17 '10 at 18:10
  • ooh yeah, good points in there. Coming from a CSS background, the idea that I can fix browser issues myself is exciting, but I can see how mucking around with the browser’s objects could get confusing. – Paul D. Waite Jul 19 '10 at 09:38
  • Thanks! However, since the question tries to set a value in Storage to true and checks if it's true, it may be a good idea to mention that keys and values can only be strings, and anything you pass as a value is implicitly converted to a string. – Timothy Zorn Mar 08 '17 at 15:53
78

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.

Stephan Hoyer
  • 4,792
  • 2
  • 29
  • 26
  • 9
    It should be the accepted answer. The accepted one will consider a stored "null" value as not set, which is wrong. – Flavien Volken Jun 05 '18 at 09:53
  • 15
    @FlavienVolken You can not have a stored `null` value though. You can have `"null"`, but the code there will not misbehave on it, while this one will fail on `length` key. – Kaiido Sep 04 '18 at 02:34
  • 2
    @Kaiido you are right, I had this behaviour because I was directly parsing the stored data and as `JSON.parse("null") === JSON.parse(null)` I had a collision. – Flavien Volken Sep 04 '18 at 14:32
  • 3
    Got the following ESLint error: "Do not access Object.prototype method 'hasOwnProperty' from target object.eslint(no-prototype-builtins)" – rfdc Jan 03 '19 at 11:32
  • This won't work if foo is not set on page load and you want to do something with foo. I think that is what the questioner was getting at, you want to check if the key `foo` exists, not if foo has a value. I have this situation, where a click event triggers `.setitem` with logic based around getItem,but it won't work until I setItem, and I can't setItem until I know foo's state (value1 or value2). In other words, check foo exits then set it to value1 if it does not without accidentally overwriting value2. – Rin and Len Feb 14 '20 at 11:56
24

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 */
Vladislav
  • 1,696
  • 27
  • 37
8
if(!localStorage.hash) localStorage.hash = "thinkdj";

Or

var secret =  localStorage.hash || 42;

Updated:

let scrollEnabled = localStorage?.scrollEnabled??true;
Deepak Thomas
  • 3,355
  • 4
  • 37
  • 39
  • JavaScript returns the first non-null or positive value Examples: [ null || "abc" ] will return "abc" [ 2 || 5 ] will return 2 [ 0 || 5 ] will return 5 [ 1 || 5 ] will return 1 etc. Hence the above code works. – Deepak Thomas May 21 '18 at 14:19
8

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";
 }
Vikas Kandari
  • 1,612
  • 18
  • 23
5

Can try something like this:

 let x = localStorage.getItem('infiniteScrollEnabled') === null ? "not found" : localStorage.getItem('infiniteScrollEnabled')
Ayush Choudhary
  • 321
  • 4
  • 10
4

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.

Prime_Coder
  • 161
  • 2
  • 14
3

For TRUE

localStorage.infiniteScrollEnabled = 1;

FOR FALSE

localStorage.removeItem("infiniteScrollEnabled")

CHECK EXISTANCE

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}
Derin
  • 1,202
  • 1
  • 15
  • 25
3

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>
Cursor
  • 111
  • 1
  • 1
  • 13
le vantard
  • 73
  • 1
2

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.

Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
1

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?
}
webmaster
  • 1,960
  • 24
  • 29
1

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

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
Mac
  • 1,432
  • 21
  • 27
1

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".

heyyy
  • 51
  • 6
0
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
zloctb
  • 10,592
  • 8
  • 70
  • 89
0

I always check if localStorage or sessionStorage is set by checking the length of them

if (sessionStorage.length > 0) {
  console.log("exists")
} else {
  console.log("not exists")
}


-3

Try this code

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

} else {

}
Moayad .AlMoghrabi
  • 1,249
  • 1
  • 11
  • 18
  • Do or do not. There is no "try". A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Apr 27 '20 at 15:33