JavaScript check if variable exists (is defined/initialized)

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

    I'm surprised this wasn't mentioned yet...

    here are a couple of additional variations using this['var_name']

    the benefit of using this method that it can be used before a variable is defined.

    if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
    if (this['elem'] !== undefined) {...}; // check if it's been declared
    if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
    
    // these will work even if you have an improper variable definition declared here
    elem = null; // <-- no var here!! BAD!
    

提交回复
热议问题