This difference is that the in
operator will walk the prototype chain, but getItem
will only return data set on the object itself.
So something like this will always return true
, even though you never set an item by that key:
'toString' in localStorage
This probably is not the intended behavior, so you will probably want to avoid it in this case.
One way you could have more-consistent code would be to use the hasOwnProperty
method. This method is available on all objects, including localStorage
. Keep in mind that is does behave differently from both getItem
and in
, as it returns boolean and will not walk the prototype chain.