views:

93

answers:

3
eval('({"suc":true})')

The above is wrong,should be:

eval('{"suc":true}')

Why?

+1  A: 
eval('({"suc":true})')

Thats not wrong actually, it will be evaluated properly.

S.Mark
+1  A: 

When trying to evaluate the interpreter sees the curly brace and thinks it is a block beginning. Enclosing in parenthesis makes it an expression and initializes an object correctly.

Murali VP
+1  A: 

I don't know what you want to achieve, but from your examples first is correct and the second throws syntax error.

eval('({"suc":true})') is the same as ({"suc":true}) and JavaScript interprets it as:

( // <- this states begining of expression
    { // <- this is hash/object literal begining
        "suc": // <- this is property name, given as string
            true // <- this is value
    }
)

So it returns new object with suc property and associated value true.

eval('{"suc":true}') is the same as {"suc":true} and is interpreted as:

{ // <- this is block begining
    "suc": // <- this is label, but incorrect, as it is given as string, not literally
        true // <- this is expression
}

If you change "suc" to suc (without parenthesis), then it would work, but it's not the same as first example.

MBO