admin管理员组文章数量:1387349
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 ing 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 ing back as true in the conditional?
I've e across other checks such as those remended by How to check for "undefined" in JavaScript?. But... why do I have to do anything even remotely 'plex' 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 .
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 ing 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 ing back as true in the conditional?
I've e across other checks such as those remended by How to check for "undefined" in JavaScript?. But... why do I have to do anything even remotely 'plex' 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/en-US/docs/Web/API/Window/sessionStorage.
Share Improve this question edited Nov 14, 2018 at 22:31 Paul 142k28 gold badges284 silver badges271 bronze badges asked Nov 14, 2018 at 22:25 Shane GannonShane Gannon 7,7569 gold badges46 silver badges73 bronze badges 01 Answer
Reset to default 13You'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
.
本文标签: javascriptWhy is if (undefined) evaluating to trueStack Overflow
版权声明:本文标题:javascript - Why is if (undefined) evaluating to true? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744563434a2612903.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论