How to check if a variable is not null?

前端 未结 9 1012
太阳男子
太阳男子 2020-11-28 17:47

I know that below are the two ways in JavaScript to check whether a variable is not null, but I’m confused which is the best practice to use.

Should I d

相关标签:
9条回答
  • 2020-11-28 18:15

    if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN

    never use number type like id as

          if (id) {}
    

    for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.

    So for id type, we must use following:

       if ((Id !== undefined) && (Id !== null) && (Id !== "")){
                                                                                    
                                                                                } else {
    
                                                                                }
                                                                                
    

    for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.

           if (string_type_variable) { }
    
    0 讨论(0)
  • 2020-11-28 18:16

    if myVar is null then if block not execute other-wise it will execute.

    if (myVar != null) {...}

    0 讨论(0)
  • 2020-11-28 18:24
    • code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
    • code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).

    Here you have all (src)

    if

    == (its negation !=)

    === (its negation !==)

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