What's the difference between:
if (localStorage.regionCode) { }
AND
if (localStorage.getItem('regionCode') !== null) { }
What's the difference between:
if (localStorage.regionCode) { }
AND
if (localStorage.getItem('regionCode') !== null) { }
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
.
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
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.
!== 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.