The answer turns out to be 110..!! Can someone tell me what is happening? But this problem wont occur if the entire expression inside the eval is enclosed in double quotes, for example if the expression was eval("5+5+10") - it would give 20 as the answer.
the thing javascript automatically conver the int operand to the string bcos converstion will done to higher datatype. so
"10+2" + 3 equls to "10+2"+"3"
now both i.e s2 and s1 are of type strings. so when you do s2+1s i.e "10"+"5+5" = "105+5" ( done concatenation of strings)
if you do eval("105+5") , you will get 120
hi, try below code
var s1 = "5+5"; var s2 = 10; alert(eval(s2) + eval(s1));
ChrisMathews
Member
12 Points
26 Posts
Ambiguous Behavior of eval()
Feb 15, 2012 03:32 AM|LINK
Hi,
consider the below piece of javascript code:
functions sample()
{
var s1="5+5";
var s2=10;
alert(eval(s2+s1));
}
The answer turns out to be 110..!! Can someone tell me what is happening? But this problem wont occur if the entire expression inside the eval is enclosed in double quotes, for example if the expression was eval("5+5+10") - it would give 20 as the answer.
Cheers,
Chris
karthicks
All-Star
32146 Points
5530 Posts
Re: Ambiguous Behavior of eval()
Feb 15, 2012 03:44 AM|LINK
now both i.e s2 and s1 are of type strings. so when you do s2+1s i.e "10"+"5+5" = "105+5" ( done concatenation of strings)
if you do eval("105+5") , you will get 120
hi, try below code
Karthick S
ChrisMathews
Member
12 Points
26 Posts
Re: Ambiguous Behavior of eval()
Feb 15, 2012 03:53 AM|LINK
A1ien51
All-Star
29935 Points
5821 Posts
Re: Ambiguous Behavior of eval()
Feb 15, 2012 02:11 PM|LINK
karthik gave you the anser,
You think it is going to be
10+5+5, but it is concatenating the two string together, than doing the math. So 10 + "5+5" turns into "105+5" and that is evaluated to 110.
Eric
ChrisMathews
Member
12 Points
26 Posts
Re: Ambiguous Behavior of eval()
Feb 16, 2012 02:59 AM|LINK
Hi,
I totally agree with you. Its an amusing thing with eval. I tried with many such expression and this i what i could infer:
if eval("x+y"+z), then it will be computed as -> yz( y and z is concatenated) + x for example eval("3+2"+3) -> 3 + 23 = 26.
similarly expression including subtractions -> eval("5-3"+2) -> 5- 32= -27
I must say it is kind of counter intuitive and is not perfectly convincing.