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

The above is wrong,should be:

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

Why?

1
  • 3
    Isn't it the other way round? Commented Dec 8, 2009 at 6:24

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 parentheses), then it would work, but it's not the same as first example.

UPDATE:

As to why array doesn't need parentheses: there is no other construct in JavaSript which would start with [ character other than array.

There would be no problem with { if it would show up in context which expects value like this:

eval('var a = {"succ": true}')

It's the same in source code (so not only in eval block): you can't create object using short notation ({ .. }) without assigning it to some variable or passing as value (to function, return statement...).

1 Comment

any idea while array doesn't require the parenthesis: var arr=eval('[true, false']);
0
eval('({"suc":true})')

Thats not wrong actually, it will be evaluated properly.

Comments

0

Have you tried to use JSON.parse('{"suc":true})) instead?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.