简体   繁体   中英

Check if JavaScript variable is undefined / false in a function

What's the best way to check in a function if a passed argument is undefined?

The return value should be:

  • If v is undefined, return false
  • If v is defined, return true if v is true, otherwise false
function isVariableFalse(v) {
    if (typeof v !== 'undefined') {     
        return false;
    }
    return v ? true: false;
}   

This issue is that when passing an undefined variable, I already get an error.

Eg

isVariableFalse(someUndefinedVariable)

Raises this error:

Uncaught ReferenceError

You have truthy and falsy notion in JavaScript.

"" is falsy and "something" is truthy. 0 is falsy and 5 is truthy.

So you can use the double negation notation if you don't want to deal with too much cases:

let my_var = <some_value>;

if(!!my_var) {
  // do something
}

The reason your function is giving you an error, is because when passing arguments to a function, javascript does not pass the variable but rather unpacks the variable and sends its value (or a reference to its value). So when you give an undefined var as an argument, there is nothing to unpack and so an error occurs. Luckily there are simple ways of checking if a var exists already, without building your own function, such as

if (v) { }

if (v !== undefined) { }

etc.

Edit Passing as a string.

function isVariableFalse(v) {
  return !!this[v] // Or you can write your own checks. Access the variable with this[v]
}

Note that this won't work for variables local to the calling function, since they only exist there. Eg. (eval wouldn't work either)

function a() {
  let c = 5;
  console.log(isVariableFalse('c')) // Will output 'false'
}

The reason you are getting Reference Error is beacuse you haven't declared SomeUndefinedVariable Which u passed in IsVariableFalse function.So you must declare a variable before passing into IsVariableFalse function like below
var SomeUndefinedVariable; //Which by default is undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM