JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1159
孤城傲影
孤城傲影 2020-11-22 00:59

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))



        
29条回答
  •  一向
    一向 (楼主)
    2020-11-22 01:31

    It depends if you just care that the variable has been defined or if you want it to have a meaningful value.

    Checking if the type is undefined will check if the variable has been defined yet.

    === null or !== null will only check if the value of the variable is exactly null.

    == null or != null will check if the value is undefined or null.

    if(value) will check if the variable is undefined, null, 0, or an empty string.

提交回复
热议问题