When trying to pass from an object defined in backticks
:
var mi_objeto = `{propiedad1: 'a', propiedad2: 'b'}`;
To a real object using the method eval
:
var objeto_real = eval(mi_objeto);
It gives me a syntax error, which is fixed if I add parentheses to the definition of mi_objeto
:
var objeto_real = eval("(" + mi_objeto + ")");
What is the syntax error when I do the eval
without the parentheses?
The error is because you are passing the string to the eval function
"{propiedad1: 'a', propiedad2: 'b'}"
. This is because you are implicitly converting to string by adding the string "(" to the objectmi_objeto
. Another way to do it is this:Note that the function
eval
receives a string as a parameter. And when receiving an object it tries to convert it to string. Your expression was equivalent toeval("{propiedad1: 'a', propiedad2: 'b'}")
, which clearly gives a syntax error.Click here to learn more about the function
eval
.About what you tell me, that's more about how complicated javascript is, not as much as with eval. For example this does not give an error:
Eval just tries to find a declaration or a variable or something in the string you pass to it.
Problem:
Why if I try to evaluate an object literal inside a string using
eval()
it gives an error ( case 1 ), while if the same object literal is enclosed in parentheses it doesn't give any problem ( case 2 ):Case 1:
Case 2:
Explanation:
If an opening bracket is not found in an expression context (as an assignment, for example), JS considers it to be an opening of a block of code. Since evaluations made by
eval()
are not considered in an expression context , the object literal passed by argument, beginning with{
, is evaluated as creating a code block containing strings and:
, resulting in a syntax error.To fix this, you must enclose the object literal definition in parentheses, since parentheses can only evaluate expressions, generating an expression context for the object literal definition starting with
{
. In this way, inside the parentheses, the{
is no longer considered as the initiation of a block of code, but as the creation of an object.The information has been taken from this English SO entry: https://stackoverflow.com/questions/3360356/why-the-open-quote-and-bracket-for-eval-jsonstring-when-parsing-json