Greetings! I have this weird output that’s not making sense to me.
I know in JS, null and undefined are loosely equal.
This is my code:
const [value, setValue] = useState(()=>{
const jsonValue = localStorage.getItem(prefixedKey); //undefined b/c nothing is in there yet. (prefixedKey is of course defined earlier in document)
console.log('jsonValue: ' + jsonValue); // jsonValue: undefined
console.log(jsonValue != null); // evaluates to true. Why?
if (jsonValue != null) return JSON.parse(jsonValue); // throws a syntax error because it expected to find something to parse and it's undefined.
});
(There’s more in this useState hook but I’ve cut out what I deemed unnecessary).
I even tested in the browser console console.log(undefined != null) and it logs false.
When something does exist in local storage, the above code works perfectly.
ooooh. I have an idea. Could it be because jsonValue is being set to the function localStorage.getItem() and a function name itself doesn’t evaluate to false?
Or am I totally off base?
Ooooh. In other circumstances, maybe this code would work. But because it’s in local storage, it is in fact storing a string that literally says “undefined.” I just did a type check and it’s a string. I bet that’s the problem.
Yes! I think I figured that out at the same time as you did. It’s literally a string that says ‘undefined’ in local storage. That has to be the reason why.