JavaScript check if variable exists (is defined/initialized)

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

    It depends on the situation. If you're checking for something that may or may not have been defined globally outside your code (like jQuery perhaps) you want:

    if (typeof(jQuery) != "undefined")
    

    (No need for strict equality there, typeof always returns a string.) But if you have arguments to a function that may or may not have been passed, they'll always be defined, but null if omitted.

    function sayHello(name) {
        if (name) return "Hello, " + name;
        else return "Hello unknown person";
    }
    sayHello(); // => "Hello unknown person"
    

提交回复
热议问题