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