Search code examples
javascriptundefinedevaluation

What value does the empty statement evaluate to?


My very fine question is: in JavaScript, what value does the empty statement evaluate to?

This is the empty statement:

;

...and if I evaluate it, I get undefined.

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

However, here is another empty statement (after a statement containing a number literal):

1;;

...and yet this appears to evaluate to 1.

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

Which surprises me.

So, what does the empty statement evaluate to?

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

The 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, the empty statement returns "no value of any type". That means it cannot return undefined (which is a value of type Undefined). I am unsure how this maps to userland code.


Solution

  • 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).