Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3618
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  长发绾君心
    2020-11-22 00:16

    If the variable hasn't been declared, you wont be able to test for undefined using a function because you will get an error.

    if (foo) {}
    function (bar) {}(foo)
    

    Both will generate an error if foo has not been declared.

    If you want to test if a variable has been declared you can use

    typeof foo != "undefined"
    

    if you want to test if foo has been declared and it has a value you can use

    if (typeof foo != "undefined" && foo) {
        //code here
    }
    

提交回复
热议问题