`prop in localStorage` versus` localStorage.getItem ('prop')! == null`
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.
source to share