JavaScript eval(“{}”) return behavior?

2019-06-24 05:21发布

问题:

According to the ECMA-262 Specification, the following statements return 1:

eval("1;;;;;")
eval("1;{}")
eval("1;var a;")

Ensuring that:

The value of a StatementList is the value of the last value producing Statement in the StatementList.

Can you explain these different returns ?

eval("{}") // undefined
eval("var a={}; a;") // {}
eval("var a={};") // undefined

What is the difference between 1; and {}; ?

回答1:

Left alone, {} is interpreted as a block, not an object. It contains no statements, so does not affect the value of, say, eval("1;{}"). To force it to be interpreted as an object, you can use parentheses:

eval("1;({})"); // {}


回答2:

It looks to me like eval is interpreting {} as the delimiters of a code block, and therefore has no inherent value.