Mayday
Mayday

Reputation: 5136

Strange js eval/template strings behaviour

Trying to answer a question in stackoverflow, I was doing some tests in my chrome console, and found the following case I am not able to understand.

var vals = ['x','y','z'];
vals.forEach(val => { eval(`var ${val} = 1; console.log('${val} = ', ${val})`);});

How can javascript know when I am refering to ${val} as the val defined in "vals" array, and when I am refering to the value it has stored each value in that array?

I mean, why it does not log:

x = x;

y = y;

z = z;

or

1 = 1;

1 = 1;

1 = 1;

Upvotes: 1

Views: 52

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78535

The template string is evaluated first, outside of the context of your eval. So you've effectively done:

eval("var x = 1; console.log('x = ', x)");
eval("var y = 1; console.log('y = ', y)");
eval("var z = 1; console.log('z = ', z)");

Which of course is just printing each variable, along with it's value.

When using eval like that, it would be useful to replace it with a console.log to see what string is actually being sent through to the call:

var vals = ['x','y','z'];
vals.forEach(val => { console.log('eval string:', `var ${val} = 1; console.log('${val} = ', ${val})`);});

Upvotes: 3

Related Questions