Alexander Solonik
Alexander Solonik

Reputation: 10230

understanding usage of eval() to evaluate boolean

I was just going through the code of timer.js HERE. and came across the following lines of code:

var paramList = ['autostart', 'time'];
for (var arg in paramList) {
    if (func[paramList[arg]] != undefined) {
        eval(paramList[arg] + " = func[paramList[arg]]");
    }
};

In the source code its all on one line, but i've made it more readable above , my difficulty is with the usage of eval, I.E. the below line of code:

eval(paramList[arg] + " = func[paramList[arg]]");

now if i add a breakpoint in chrome to the above line and go to the console and paste the line of code i get the following:

true 

How come ? lets have a close look at the statement again:

eval(paramList[arg] + " = func[paramList[arg]]");

what is the + doing here ? converting paramList[arg] to a string , in which case eval is being used as follows:

eval("paramList[arg] = func[paramList[arg]]");

?

or is the plus sign being used for concatenation purpose ? (which i think is very unlikely !)

I have read MDN eval(), but still had doubts.

can anybody explain the breakdown of that statement please ?

Thank you.

Upvotes: 0

Views: 112

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

eval takes a string. What you have:

eval(paramList[arg] + " = func[paramList[arg]]");

The + is just string concatenation.

Is equivalent to:

var code = paramList[arg] + " = func[paramList[arg]]"
eval(code);

So I'd say it should be equivalent to:

global[paramList[arg]] = func[paramList[arg]];

Or, in this particular example (with var paramList = ['autostart', 'time'];)):

if (func['autostart'] != undefined)
    autostart = func['autostart'];

if (func['time'] != undefined)
    time = func['autostart'];

Upvotes: 4

Related Questions