How to check if a variable is not null?

前端 未结 9 1062
太阳男子
太阳男子 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) { }
    

提交回复
热议问题