Is empty string treated as falsy in javascript?

后端 未结 5 1740
渐次进展
渐次进展 2021-01-17 01:58

I\'ve noticed that if you have a statement as the following:

var test = \"\" || null

test will evaluate to null b

相关标签:
5条回答
  • 2021-01-17 02:30

    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 */
    

    SEE HERE

    0 讨论(0)
  • 2021-01-17 02:38

    Yes an empty string is falsy, however new String("") is not.

    Note also that it's well possible that

    if (x) { ... }
    

    is verified, but that

    if (x == false) { ... }
    

    is verified too (this happens for example with an empty array [] or with new String("")).

    0 讨论(0)
  • 2021-01-17 02:40

    Does javascript treat empty string as either a falsy or null value, and if so why?

    Yes it does, and because the spec says so (§9.2).

    Isn't an empty string still an object

    No. An primitive string value is no object, only a new String("") would be (and would be truthy)

    0 讨论(0)
  • 2021-01-17 02:43

    A string isn't an object in JS. Other "falsy" values are: 0, NaN, null, undefined.

    0 讨论(0)
  • 2021-01-17 02:48

    String is not an object, it's a primitive like number or boolean.

    The empty string, NaN, +0, -0, false, undefined and null are the only values which evaluate to false in direct boolean conversion.

    0 讨论(0)
提交回复
热议问题