JavaScript check if variable exists (is defined/initialized)

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

    There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.

    var values = typeof variable !== 'undefined' ? variable : '';
    

    Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.

    If you wanted to check variable shouldn't be undefined or null. Then perform below check.

    When the variable is declared, and if you want to check the value, this is even Simple: and it would perform undefined and null checks together.

    var values = variable ? variable : '';
    

提交回复
热议问题