2

The answer to this question recommends:

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

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

'prop' in localStorage

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

Community
  • 1
  • 1
Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

2 Answers2

3

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.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
1

You should use the getItem(prop) !== null test because in cannot distinguish between the values stored in localStorage from the non-enumerable properties of that object (or those inherited from its prototype chain).

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

Alnitak
  • 334,560
  • 70
  • 407
  • 495