Error Syntax in Javascript eval

1

When trying to move from an object defined in backticks :

var mi_objeto = '{propiedad1: 'a', propiedad2: 'b'}';

To a real object using the eval method:

var objeto_real = eval(mi_objeto);

I get a syntax error, which is fixed if I add parentheses to the definition of mi_objeto :

var objeto_real = eval("(" + mi_objeto + ")");

Why is the syntax error due when I do the eval without the parentheses?

    
asked by Ibrahim Hernández Jorge 03.07.2017 в 21:49
source

2 answers

1

Problem:

Why if I try to evaluate a literal of an object within a string using eval() it gives an error ( case 1 ), whereas if the same literal of the object is enclosed in parentheses it does not give no problem ( case 2 ):

Case 1:

var mi_objeto = eval('{propiedad1: 'a', propiedad2: 'b'}');
console.log(typeof mi_objeto);
console.log(mi_objeto);

Case 2:

var mi_objeto = eval('({propiedad1: 'a', propiedad2: 'b'})');
console.log(typeof mi_objeto);
console.log(mi_objeto);

Explanation:

If a bracket opening is not found in an expression context (such as an assignment, for example), JS considers it as opening a block of code. Since evaluations performed by eval() are not considered in an expression context , the literal of the object passed by argument, starting with { , is evaluated as creation of a block of code that contains strings and : , resulting in a syntax error.

To solve this, the definition of the object literal must be included in parentheses, since the parentheses can only evaluate expressions, generating an expression context for the definition of the literal of the object that starts 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 obtained from this SO entry in English: link

    
answered by 04.07.2017 / 03:09
source
1

The error is because you are passing the eval function to the string "{propiedad1: 'a', propiedad2: 'b'}" . This is because you implicitly convert to string by adding the string "(" with the object mi_objeto .) Another way to do it is this:

var mi_objeto = '{propiedad1: 'a', propiedad2: 'b'}';
var objeto_real = eval('mi_objeto');
console.log(objeto_real);

Keep in mind 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 to eval("{propiedad1: 'a', propiedad2: 'b'}") , which clearly gives a sintaxix error.
Click here to Learn more about the eval function.

About what you tell me, and that is more about how complicated javascript is, not as much as with eval. For example this does not give an error:

({propiedad1: 'a', propiedad2: 'b'})
While this is:

{propiedad1: 'a', propiedad2: 'b'}

Eval just try to find a statement or a variable or something in the string you pass.

    
answered by 03.07.2017 в 21:58