0

There are lot of info to check for "undefined" normal vars in JavaScript, but I need to check for an eval(var) like:

var Hello_0 = "Hello 0 !";

console.log(" Hello_0 is: " + eval("Hello_"+0));

var dinamyc_var = "Hello_"+1;

//None of the next conditionals is triggered///
if (eval(dinamyc_var) === undefined) {
     console.log(" dinamyc_var is undefined ");
} 
if (eval(dinamyc_var) === null) {
     console.log(" dinamyc_var is null ");
}
if ( typeof eval(created_node) === undefined ) {
     console.log(" dinamyc_var is typeof undefined ");
}
if ( typeof eval(created_node) === null ) {
     console.log(" dinamyc_var is typeof null ");
}

console.log(" dinamyc_var is: " + eval(dinamyc_var));

https://jsfiddle.net/mczdrv5t/

The console show the value of eval("Hello_"+0) because was declared, but the console show the next error when try to call eval("Hello_"+1) that not was declared. I need to handle possible undeclared vars.

Uncaught ReferenceError: Hello_1 is not defined at eval (eval at ....

Extrange planet
  • 228
  • 3
  • 13
  • 3
    In practice, you never need — or _want_, really — dynamic variable names. Use a simple object instead: `const obj = { Hello_0: "Hello 0 !" };` … `console.log(obj["Hello_" + 0]); console.log(obj.hasOwnProperty("Hello_" + 1));`, etc., or, for indexed structures, an array. See ["Variable" variables in JavaScript](/q/5187530/4642212). With `eval` and the necessary `try`–`catch` you only make everyone’s life unnecessarily hard, including your own. – Sebastian Simon Oct 27 '21 at 08:34
  • [Off-topic]: `dinamyc` is actually spelled `dynamic` – FZs Oct 27 '21 at 08:46

1 Answers1

3

Don't use eval. If you need to store values of varying names, use an object instead:

const values = {}

values["Hello_0"] = "Hello 0 !"

if (values["Hello_" + 1] === undefined) {
  // ...
}

As a sidenote, if (eval('typeof ' + dynamic_var) === 'undefined') would work but again, don't use eval.

Don't do window[dynamic_var] = ... to store global variables either, the names might clash with existing globals.

DustInComp
  • 1,742
  • 8
  • 18
  • Thanks by the "typeof" eval suggestion! I can`t use an object in my special case. – Extrange planet Oct 27 '21 at 09:55
  • What's your special case? Are the variables already defined in global scope by someone else? in that case, `window[varname] == undefined` would still be cleaner. – DustInComp Oct 27 '21 at 11:48