Why can a string like "{opacity: 1.0, width: '132px'}" not be evaluated using eval() as is?
eval("{opacity: 1.0, width: '132px'}");
// invalid label
// {opacity: 1.0, width: '132px'}
// ---------------ꜛ
eval("v = {opacity: 1.0, width: '132px'}");
// works!
Because the text occurs where a statement or block is expected, not an expression, and so the
{denotes the beginning of a block, not the beginning of an object initializer. (And thenopacity:is interpreted as a label followed by the statement separator [a comma], and thenwidth:looks like another label, which is not valid there.)Putting it in parentheses changes the parsing context so that an expression is expected, and so the
{opens the initializer. (This is the same reason you see self-executing anonymous functions wrapped in parentheses, e.g.(function(){ ... })();rather than justfunction(){ ... }();.)