0

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>
CheeseFlavored
  • 1,384
  • 1
  • 14
  • 23
  • 3
    https://developer.mozilla.org/en-US/docs/Glossary/Falsy – epascarello Jan 22 '19 at 17:51
  • 1
    Possible duplicate of [JavaScript checking for null vs. undefined and difference between == and ===](https://stackoverflow.com/questions/5101948/javascript-checking-for-null-vs-undefined-and-difference-between-and) – RyanZim Jan 22 '19 at 17:52
  • So, if I understand this correctly, ! means "falsy" and if a value doesn't exist in local storage, it is NULL. And since null is a falsy value, it would be perfectly acceptable to use if (!x) in this situation, correct? – CheeseFlavored Jan 22 '19 at 18:03

2 Answers2

1

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

WilliamNHarvey
  • 1,890
  • 2
  • 12
  • 23
0

Is not exactly the same... This !x is checking for a truthy value but anything between null, undefined, or even 0 will return false.

There is also a significant difference between == and === where == will try an automatic type conversion in order to check if the values are in some way compatible, but the === will check for an strict equality.

You can learn more about the JavaScript types and their interaction with the different operators in this link Values, Types, and Operators

David Gomez
  • 2,672
  • 2
  • 15
  • 27