`prop in localStorage` versus` localStorage.getItem ('prop')! == null`

The answer to this one recommends:

localStorage.getItem('prop') !== null

      

However, I want my code to be consistent and I want to use:

'prop' in localStorage

      

Is there something wrong with the second form? In terms of speed, it should be marginally faster.

+3


source to share


2 answers


The difference is that the operatorin

will traverse the prototype chain, but getItem

will only return the dataset on the object itself.

So, something like this will always return true

, even though you never set the item with that key:

'toString' in localStorage

      



This is probably not intentional behavior, so you probably want to avoid it in this case.

One way to get more consistent code would be to use thehasOwnProperty

. This method is available for all objects including localStorage

. Be aware that this does not behave the same as from getItem

and in

, since it returns a boolean value and will not traverse the prototype chain.

+4


source


You must use a test getItem(prop) !== null

because you in

cannot distinguish between the values ​​stored in localStorage

that object's non-enumerable properties (or those inherited from its prototype chain).



A good example is that 'getItem' in localStorage === true

+1


source







All Articles