Error when passing undefined variable to function?

后端 未结 1 1335
野趣味
野趣味 2020-12-09 21:03

I am trying to create a reusable function that checks if a variable is undefined or not. The strange thing is that it does not work when I pass the variable to the function

相关标签:
1条回答
  • 2020-12-09 21:31

    You cannot use a variable that hasn't been declared unless it's in a typeof test

    When you try to pass a variable that hasn't been declared into a function, that is considered using that undeclared variable. You'll notice that the error is in the caller, not inside isDefined

    You need to run the check for

    if (typeof sdsdsd !== 'undefined')
    

    before you pass it into the function. Basically that means you can't write a isDefined function that accepts undeclared variables. Your function can only work for undefined properties (which are OK to pass around)

    However, I am curious, what is the real world case where you're passing a variable that doesn't exist? You should declare all your variables and they should exist already. Had you declared var sdsdsds it would exist with the value of undefined and your isDefined function would work just fine.

    0 讨论(0)
提交回复
热议问题