Skip to content Skip to sidebar Skip to footer

Check If A Variable Exists Within Local Scope By Name As String?

I'd like to find out if there is a variable that exists in the local scope with a given name as a string. Is there way to do something like this?: var name = 'myVariable'; functio

Solution 1:

I'm going to piggyback on Bandrami's answer and my comment as I believe it to be the only way to accomplish what you are trying to do. Yes, I know that I'm using eval, but I don't believe there is any option.

if (typeofeval(name) !== 'undefined' && typeofwindow[name] === 'undefined'){ 
   // variable exists in this scope 
}

Solution 2:

if (typeofeval(name) === 'undefined')

Though there are some corner cases there (like a variable actually named 'undefined')...

(Or I may be completely missing your point...)

Post a Comment for "Check If A Variable Exists Within Local Scope By Name As String?"