Why the heck is null != undefined evaluating to true in my code?

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.

What could be going on here?

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?

It is a string?

undefined != null
// false
undefined !== null
// true
'undefined' != null
// true
1 Like

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.

Sound about right. I’d suggest using a typeof check for debugging code like this as well.

You may also want to be careful when relying on type coercion, it can get a little odd at times.

So true. JS type coercion can lead to unexpected outcomes unless you’re an expert on the subject lol. Well thank you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.