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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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: