0

Working of JavaScript global function eval()

Hello everyone, I recently came accross a question in the playground. It was stated as follows: var x = "2*2"; var y = 4; var z = eval(x+y); alert(z); I got this wrong. After the competition, When I saw the answer it said 48. So, I googled for eval() and found that it evaluate a specified string as JavaScript. Oh, ok. Then z = 2*2+4; seems logical which come out to be 16. Can anyone help me figure out the how the answer was 48.

29th Apr 2020, 8:18 AM
DoMan
DoMan - avatar
4 Respostas
+ 2
I assume the concatenation takes place before the string is passed off to eval(). So all eval() ever saw was the complete string "2*24" which it then processes as a JavaScript expression. But I do agree that JavaScript's type-system is very perplexing and the type conversions odd at times. If I was put on the spot I'd probably lose that competition as well.
29th Apr 2020, 9:04 AM
Damyian G
Damyian G - avatar
+ 2
I don't know JavaScript but my guess is that because 'x' is surrounded by double quotes it's considered a string type so the + operator morphed into a string concatenation of 'x' and 'y', so the expression turned into 2*24 which was evaluated as 48.
29th Apr 2020, 8:46 AM
Damyian G
Damyian G - avatar
+ 1
Damyian G This seems like a logical reasoning. But the eval() functions definition says it evaluates string as javascript. From this point of view it should remove the " from 2*2 which turns them into numbers. Then calculating 2*2+4 as numbers should give 16. Your reasoning is correct that's the only way to get 48 but now my question is why did it treat the 2 as a string rather than a number.
29th Apr 2020, 8:45 AM
DoMan
DoMan - avatar
+ 1
Yes, that exactly what guess Damyian G... the expression passed at argument is evaluated first and give the string "2*24" ^^ "2*2" is never "turned to number"... if it was the result would be the special number value 'NaN' (wich stands for Not a Number). That's what would happen if you've done y+x rather than x+y (2+NaN is NaN too, and eval should treat it as the steing "NaN", finally returning the number NaN ;P)
29th Apr 2020, 9:26 AM
visph
visph - avatar