+ 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?

26th Mar 2017, 12:41 AM
Wisdom Abioye
Wisdom Abioye - avatar
3 Réponses
+ 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
26th Mar 2017, 1:17 AM
Squidy
Squidy - avatar
+ 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.
26th Mar 2017, 1:34 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar