2

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

4 Answers 4

7

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 || {};
Sign up to request clarification or add additional context in comments.

Comments

1

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

Eval is executed in separate context.

Comments

0

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';
}

1 Comment

This will always result in answer being equal to 'Foo bar', even if it was defined before (for example in the closure). Google 'variable hoisting js'
0
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]);

2 Comments

The first example works. jsfiddle.net/kQYTy However in the second one I jumped to conclusions.
The reason the first example works, is because the variable is "hoisted" to the top in their context. adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting Just if(someUndefinedVariable === undefined){} will fail though, since you don't declare it at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.