How can I check whether a variable is defined in Node.js?

前端 未结 6 461
不知归路
不知归路 2021-01-31 01:18

I am working on a program in node.js which is actually js.

I have a variable :

var query = azure.TableQuery...

looks this line of the

6条回答
  •  情话喂你
    2021-01-31 01:52

    Determine if property is existing (but is not a falsy value):

    if (typeof query !== 'undefined' && query !== null){
       doStuff();
    }
    

    Usually using

    if (query){
       doStuff();
    }
    

    is sufficient. Please note that:

    if (!query){
       doStuff();
    }
    

    doStuff() will execute even if query was an existing variable with falsy value (0, false, undefined or null)

    Btw, there's a sexy coffeescript way of doing this:

    if object?.property? then doStuff()
    

    which compiles to:

    if ((typeof object !== "undefined" && object !== null ? object.property : void 0) != null) 
    
    {
      doStuff();
    }
    

提交回复
热议问题