views:

193

answers:

4
+1  Q: 

JavaScript eval

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

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

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

+3  A: 

The extra parentheses are wrong, this is correct:

eval('caption="Summer";alert(caption)');
frunsi
+8  A: 
Uncaught SyntaxError: Unexpected token ;

The outer parentheses make no syntactical sense. Try this:

eval('caption="Summer";alert(caption)');
Aistina
Correct, parentheses (the Grouping Operator) can be used only to evaluate *one expression*, more info: http://bclary.com/2004/11/07/#a-11.1.6
CMS
+3  A: 

Chrome console:

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

This works:

eval('caption="Summer"; alert(caption)')
Jonathon
A: 

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

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

Anil Namde
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?
frunsi