JavaScript check if variable exists (is defined/initialized)

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

    The most robust 'is it defined' check is with typeof

    if (typeof elem === 'undefined')
    

    If you are just checking for a defined variable to assign a default, for an easy to read one liner you can often do this:

    elem = elem || defaultElem;
    

    It's often fine to use, see: Idiomatic way to set default value in javascript

    There is also this one liner using the typeof keyword:

    elem = (typeof elem === 'undefined') ? defaultElem : elem;
    

提交回复
热议问题