1

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;

1 Answer 1

3

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})`);});

Sign up to request clarification or add additional context in comments.

Comments

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.