JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1219
孤城傲影
孤城傲影 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:23

    You can also use !! before a variable to check if it's defined. E.g.

    let dog = "woof";
    let chineseCat; // Undefined.
    console.log("1.");
    console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
    
    chineseCat= "mao"; // dog and chineseCat are now defined.
    console.log("2.");
    console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
    

    Output:

    1.
    Both are NOT defined
    2. 
    Both are defined
    

提交回复
热议问题