Falsey values in JavaScript

后端 未结 6 1324
情歌与酒
情歌与酒 2020-11-27 06:13

I had an interesting interview question today that stumped me a little. I was asked about falsey values. So undefined, NaN, null, 0, and an empty string all evaluate to fals

6条回答
  •  轮回少年
    2020-11-27 06:50

    One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.

    Suppose you want to test for the availability of a new property; when this property can actually have a value of 0 or "", you can't simply check for its availability using

    if (!someObject.someProperty)
        /* incorrectly assume that someProperty is unavailable */
    

    In this case, you must check for it being really present or not:

    if (typeof someObject.someProperty == "undefined")
        /* now it's really not available */
    

    Also be aware that NaN isn't equal to anything, even not to itself (NaN != NaN).

提交回复
热议问题