Search code examples
javascripteval

JavaScript eval() not working with variable name


why eval() is not executing my code?

for (var i = 1; i <= 3; i++) {
  str = "var foo_" + i + "_bar = " + i;
  eval(str);
}
console.log(foo_1_bar);
console.log(foo_2_bar);
console.log(foo_3_bar);


Solution

  • The variable foo_2_bar is not declared at that iteration (i = 1). You need to put the console.log(...) outside of the loop.

    I assume you're playing with js because eval is a little dangerous.

    for (var i = 1; i <= 3; i++) {
      str = "var foo_" + i + "_bar = " + i;
      eval(str);
    }
    console.log(foo_1_bar);
    console.log(foo_2_bar);
    console.log(foo_3_bar);