2

What's the difference between:

if (localStorage.regionCode) { }

AND

if (localStorage.getItem('regionCode') !== null) { }
A_B
  • 1,009
  • 3
  • 15
  • 37

3 Answers3

1

In JavaScript you have truthy and falsey. This means that every condition converts in an condition-statement to a boolean and represents true or false.

Explenation

If localStorage.regionCode is an empty string if(localStorage.regionCode) would converts to false otherwise true.


For more details you could read the blog post about truthy and falsey

Roman
  • 4,922
  • 3
  • 22
  • 31
0

In first case it is checking if there exist any storage item with name regionCode. In this case it will be undefined if there is no key by name regionCode in localStorage & in second case it is checking the value of the localStorage key regionCode which will return null.

See the information listed here.

SimplyComplexable
  • 1,116
  • 11
  • 19
brk
  • 48,835
  • 10
  • 56
  • 78
0

!== null condition will be always fulfilled if only regionCode prop exists.

Similar situation with localStorage.regionCode with a slight difference, that it won't pass if regionCode is an empty string.

kind user
  • 40,029
  • 7
  • 67
  • 77