Home > Software engineering >  What value does the empty statement evaluate to?
What value does the empty statement evaluate to?

Time:08-15

I am unsure what an empty statement actually evaluates to. Depending on my tests, I get different values when evaluating an empty statement with different setups. Does the empty statement evaluate to undefined or something else?

console.log(eval('1')) // 1
console.log(eval('1;')) // 1
console.log(eval('1;;')) // 1 (!)
console.log(eval(';')) // undefined (!)
console.log(eval('')) // undefined (!)

Edit:

Spec says the empty statement returns "empty". I don't know what that means yet.

Spec also says:

When the term “empty” is used as if it was naming a value, it is equivalent to saying “no value of any type”.

So, based on the above discoveries, the empty statement returns "no value of any type". That means it cannot return undefined (which is a value of type Undefined). Unsure of how this interacts with userland behavior.

CodePudding user response:

The empty statement returns nothing at all (empty: "no value of any type"). A statement list, like the one in the body of a Script that eval is parsing the code as, returns the value of the last statement that did return anything:

The value of a StatementList is the value of the last value-producing item in the StatementList. For example, the following calls to the eval function all return the value 1:

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

An empty statement list, empty script, empty block, or statement list containing no value-producing statements evaluates to empty.

The PerformEval operation then converts that empty value to undefined in step 30:

If result.[[Type]] is normal and result.[[Value]] is empty, then
  Set result to NormalCompletion(undefined).

  • Related