JavaScript check if variable exists (is defined/initialized)

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

    Try-catch

    If variable was not defined at all, you can check this without break code execution using try-catch block as follows (you don't need to use strict mode)

    try{
      notDefinedVariable;
    } catch(e) {
      console.log('detected: variable not exists');
    }
    
    console.log('but the code is still executed');
    
    notDefinedVariable; // without try-catch wrapper code stops here
    
    console.log('code execution stops. You will NOT see this message on console');

    BONUS: (referring to other answers) Why === is more clear than == (source)

    if( a == b )

    if( a === b )

提交回复
热议问题