Search code examples
javascriptlocal-storagelogical-operatorscomparison-operators

javascript - NOT vs NULL with Local storage


So I want to get a variable from local storage. If it doesn't exist in local storage, then I want to create that variable. I was using if (x==null) to see if it existed, then I noticed if(!x) has the same result. Is it ok to use ! in this situation? I didn't know ! and null are the same here. Also when checking for null, should I use === or is == ok?

Here's two examples that give me the same results.

<script>
localStorage.clear();

a=localStorage.getItem('a');if (!a) a='hello';
alert(a);

x=localStorage.getItem('x');if (!x) x=0.7;
alert(x);

</script>

<script>
localStorage.clear();

a=localStorage.getItem('a');if (a==null) a='hello';
alert(a);

x=localStorage.getItem('x');if (x==null) x=0.7;
alert(x);

</script>

Solution

  • https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem

    localStorage.getItem returns null if the key doesn't exist. So a === null would be the most specific check for if the key didn't exist. However, null is falsy in javascript. So you could reduce the check to this:

    a = localStorage.getItem('a') || 'hello';

    Which functions the same as your if with the not operator