0

I'd like to create a function wich have a var in argument, if the var is defined return the var value else return the var name

I try

test = function(variable){
    try{
        if ( typeof(variable) != "undefined" ) {
            return 'true'
        }
        return 'false'
    }catch(e){
        console.log(e);
    }

}

but if I have an undefined var the function isn't called and I have the undefined function error.

I would like to know how to have the variable name too

Thanks :)

1 Answer 1

1

don't use var as your parameter. It it a reserved word in JavaScript and doesn't describe what the variable is used for.

how about:

var test = function(variable) {
  if (!variable) return false;
  return variable;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it works fine, I change var in my post, Do you know how to return the variable name instead of false ?
what do you mean with 'variable name'? if there is no variable you cannot return the name. Or do you just want return 'variable'?
test(definedVar)=> definedVar: value . test(undefinedVar)=> undefinedVar . But from my searchs and as you say I can't get a variable name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.