Riz
Riz

Reputation: 10246

define a variable if its undefined using Javascript

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

Answers (4)

Martin Hansen
Martin Hansen

Reputation: 5224

if(someUndefinedVariable === undefined){
    var someUndefinedVariable = 'whatever you want' 
}
alert(someUndefinedVariable) //obviously not undefined anymore

EDIT: code below is not working

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

Xavier
Xavier

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

jfriend00
jfriend00

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

kirilloid
kirilloid

Reputation: 14304

if (typeof answer == "undefined") var answer = {};

Eval is executed in separate context.

Upvotes: 1

Related Questions