JavaScript check if variable exists (is defined/initialized)

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

    I use two different ways depending on the object.

    if( !variable ){
      // variable is either
      // 1. '';
      // 2. 0;
      // 3. undefined;
      // 4. null;
      // 5. false;
    }
    

    Sometimes I do not want to evaluate an empty string as falsey, so then I use this case

    function invalid( item ){
      return (item === undefined || item === null);
    }
    
    if( invalid( variable )){
      // only here if null or undefined;
    }
    

    If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.

提交回复
热议问题