Reputation: 10246
How to defined a variable in Javascript, if its not defined. I tried:
var str = "answer";
if(eval(str) == undefined)
eval("var " + str + " = {}");
alert(answer);
but its displaying error: ReferenceError: answer is not defined
Upvotes: 2
Views: 5849
Reputation: 5224
if(someUndefinedVariable === undefined){
var someUndefinedVariable = 'whatever you want'
}
alert(someUndefinedVariable) //obviously not undefined anymore
or if you do not know the variable name at time of writing the code
var propertyName = 'answer'; //could be generated during runtime
if(window[propertyName] === undefined){
var window[propertyName] = 'whatever you want';
}
alert(window[propertyName]);
Upvotes: 0
Reputation: 274
You should use typeof
with ===
operator and 'undefined'
(to be sure that nobody overwrote undefined variable) to check if variable is undefined and when it is then assign value to it:
if (typeof answer === 'undefined') {
var answer = 'Foo bar';
}
Upvotes: 0
Reputation: 707198
If you have to do it from a name that's in a javascript variable (that isn't known ahead of time), then you can do it like this:
var str = "answer";
if (typeof window[str] == "undefined") {
window[str] = {};
}
This uses the fact that all global variables are properties of the window object (in a browser).
If you know the name of the variable ahead of time, then you can simply do this:
var answer = answer || {};
Upvotes: 7
Reputation: 14304
if (typeof answer == "undefined") var answer = {};
Eval is executed in separate context.
Upvotes: 1