Why doesn't this eval call alert("Summer")?
eval('(caption="Summer";alert(caption))');
Does it have something to do with the quotes in "Summer"?
Richard JP Le Guen
28.8k8 gold badges93 silver badges121 bronze badges
asked Feb 14, 2010 at 23:33
JamesBrownIsDead
1152 silver badges4 bronze badges
4 Answers 4
Uncaught SyntaxError: Unexpected token ;
The outer parentheses make no syntactical sense. Try this:
eval('caption="Summer";alert(caption)');
answered Feb 14, 2010 at 23:37
Aistina
12.7k14 gold badges73 silver badges91 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Christian C. Salvadó
Correct, parentheses (the Grouping Operator) can be used only to evaluate one expression, more info: bclary.com/2004/11/07/#a-11.1.6
headacheCoder
@CMS No, that's wrong. The grouping operator can evaluate infinite expressions (separated by the comma operator) as long as each expression returns exactly one value. The grouping operator will then return the last returned value, e.g.
(alert("foo"), alert("bar"), window.foo = "bar", 1, 2 ,3) will evaluate all grouped expressions but only return 3. So (@Aistina) the correct answer would be that the semicolon inside the parantheses makes no syntactical sense: eval('(caption="Summer",alert(caption))');Christian C. Salvadó
@headacheCoder, the expressions will be evaluated in your example, but at the end, syntactically at the highest level (at the level where the grouping operator is evaluated) it is just one single expression, the comma operator allows this, you can check its grammar here: es5.github.com/#x11.14 (it's a recursive production) and you can try your example in the following parser: esparser.qfox.nl and you will see that the parentheses are holding just an Expression token at this level.
Chrome console:
eval('(caption="Summer";alert(caption))')
SyntaxError: Unexpected token ;
This works:
eval('caption="Summer"; alert(caption)')
answered Feb 14, 2010 at 23:38
Jonathon Faust
12.6k4 gold badges53 silver badges63 bronze badges
Comments
The extra parentheses are wrong, this is correct:
eval('caption="Summer";alert(caption)');
answered Feb 14, 2010 at 23:36
Frunsi
7,1575 gold badges39 silver badges43 bronze badges
Comments
A more better way to do this and avoid syntax problem is to do following,
eval(function(){var x="test"; alert(x)}());
answered Feb 15, 2010 at 8:23
Anil Namde
6,64812 gold badges69 silver badges101 bronze badges
1 Comment
Frunsi
But here the eval is superfluous. Eval only makes sense if the code to evaluate is available as a string from some source (e.g. ajax call or even user input). But you don't need eval if you already have the code as code. Right?
lang-js
,operator:eval('(caption="Summer",alert(caption))');