4

I'm new to JavaScript and have hit what seems to be an obvious issue.

const item = sessionStorage.getItem('item'); // undefined
if (item) {
    return item;
}

In the Chrome debugger I can see that item is coming back as undefined. I would expect the conditional to fail. To my surprise it's evaluating to true.

I thought I'd already tested this out. Why would it be coming back as true in the conditional?

I've come across other checks such as those recommended by How to check for "undefined" in JavaScript?. But... why do I have to do anything even remotely 'complex' for a simple check like this? The above approach seems so simple and elegant I'm reluctant to lose it.

I'm also seeing this approach in an example on https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage.

0

1 Answer 1

13

You're not getting the value undefined from sessionStorage, but the string "undefined", which is truthy just like any other non-empty string.

I know you're not getting the value undefined because that is impossible. sessionStorage.getItem can only return a string or null. Also note that setItem will coerce its argument to a string, so sessionStorage.setItem('item', undefined) sets item to the string "undefined".

If you want to remove an item you should use sessionStorage.removeItem('item'); instead of setting it to undefined.

Sign up to request clarification or add additional context in comments.

1 Comment

And you're 100% right. Found that the value was set to the string "undefined" in sessionStorage. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.