JavaScript check if variable exists (is defined/initialized)

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

    In the particular situation outlined in the question,

    typeof window.console === "undefined"
    

    is identical to

    window.console === undefined
    

    I prefer the latter since it's shorter.

    Please note that we look up for console only in global scope (which is a window object in all browsers). In this particular situation it's desirable. We don't want console defined elsewhere.

    @BrianKelley in his great answer explains technical details. I've only added lacking conclusion and digested it into something easier to read.

提交回复
热议问题