2

Why doesn't this eval call alert("Summer")?

eval('(caption="Summer";alert(caption))');

Does it have something to do with the quotes in "Summer"?

2
  • Why do you have parentheses around all the stuff inside the quotes? Commented Feb 14, 2010 at 23:35
  • If you want to sequence statements inside an expression use the , operator: eval('(caption="Summer",alert(caption))'); Commented Feb 15, 2010 at 0:50

4 Answers 4

13
Uncaught SyntaxError: Unexpected token ;

The outer parentheses make no syntactical sense. Try this:

eval('caption="Summer";alert(caption)');
Sign up to request clarification or add additional context in comments.

3 Comments

Correct, parentheses (the Grouping Operator) can be used only to evaluate one expression, more info: bclary.com/2004/11/07/#a-11.1.6
@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))');
@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.
4

Chrome console:

eval('(caption="Summer";alert(caption))')
SyntaxError: Unexpected token ;

This works:

eval('caption="Summer"; alert(caption)')

Comments

2

The extra parentheses are wrong, this is correct:

eval('caption="Summer";alert(caption)');

Comments

0

A more better way to do this and avoid syntax problem is to do following,

eval(function(){var x="test"; alert(x)}());

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.