-9

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.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • `1;;` contains an empty statement. – Ben Aston Aug 15 '22 at 10:43
  • 4
    What even is the question here? Does *it* evaluate to *something* - as you have run the code you already know the answer. – luk2302 Aug 15 '22 at 10:45
  • @JaromandaX Please explain. – Ben Aston Aug 15 '22 at 10:45
  • The semicolon delineates a statement. So the first statement is `1;` (which trivially evaluates to `1`). The second is `;`? – Ben Aston Aug 15 '22 at 10:47
  • One semicolon doesn't create e statement. Semicolons are more like separators than statement creators. – Konrad Aug 15 '22 at 10:48
  • [empty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/Empty) – Konrad Aug 15 '22 at 10:59
  • 2
    @JaromandaX `1;;` is two statements, the first is `1;` the second is `;` (an empty statement). `;;` is two empty statements. There is not "automatic semicolon removal" as a counterpart to automatic semicolon insertion. – Bergi Aug 15 '22 at 11:32

1 Answers1

5

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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375