0

Like let's say you have a function like

function variableFunTime(varname){
    console.log("I ran a function, even if the variable was bad");
};

and you have the variables

var aValidVar = "123";
var aValidVar2 = "456";

and you run the function like

variableFunTime(NopeNotValid);

A use case for this maybe would be a function to check whether or not a variable exists or something, but it seems impossible to even reference an invalid variable without just getting a ReferenceError and the function never running.

function IsThisAValidTicket(ticket){
   //check if ticket exists and return false if not
}

The reason other questions that have been marked as the same as this are different is that the solutions defined from them don't work inside functions

Melissa
  • 274
  • 1
  • 9
  • 3
    You are correct. It throws a `ReferenceError`, but why would the variable be undeclared in the first place? Can you explain the context a bit better so we can come up with a solution? – Joseph Marikle Jul 02 '15 at 19:54
  • Yes I'm aware of if, but it doesn't work if the function doesn't run. @JosephMarikle I'll add an example in the question. – Melissa Jul 02 '15 at 19:55
  • @Melissa: `typeof` is the only thing that works with undeclared variables. If you're doing anything else, such as a function call, it throws an exception. You won't get around that. – Bergi Jul 02 '15 at 20:00
  • But why do you even check if it exists? it will never exist! if you are creating a variable in a different scope, then you need to make it global. – loli Jul 02 '15 at 20:00
  • You should preferebly always declare all your variables within the scope you're going to call them. Alternatively as closures declared VERY close to where you're calling them from, or as very carefully selected globals. If you need to verify that a variable is even declared before running a function, you're probably doing something very wrong (unless it's a framework/library). Properties is another matter though. – Jan Jul 02 '15 at 20:00

1 Answers1

0

You could assign it to a valid var and call the function passing the valid one:

var validVar;

try {
    validVar = invalidVar;
} catch (e) {}

functionToCall(validVar);
gfpacheco
  • 2,655
  • 2
  • 33
  • 46