+ 12
Can Javascript Ninja explain this : alert(eval('2*2' + 4)); // 48
alert(eval('2*2' + 4)); // 48 I came across this in a challenge. The result is unbelievable because I expect 8 to be the answer. Is Javascript cheating on me?
2 Answers
+ 10
'2*2' is a string, so the + operator is actually concatenating that 4 onto the end, so you get "2*24". That evaluates to 48.
You'd be right if the parentheses were a little bit different. E.g., eval('2*2') + 4 = 8
+ 10
To be more clear, as the eval() function takes a string as input, it converts it's input into a single string thus making the input 2*24 in this case.