Search code examples
javascriptv8

Why can't I assign an empty code block to a variable in Javascript?


I'm using V8 (via Chrome) to test this. In Javascript, a code block evaluates to whatever the last value in the code block evaluates to. I wanted to see what would happen if I assigned a variable to an empty code block.

// example of code block evaluating to last value in the block
> {1;2;3};
3

// This won't work, it returns an empty object,
// not an empty code block.
> var emptyBlock = {};
> emptyBlock;
Object object

Eventually, I figured out how to specify that I want an empty code block, not an empty object.

> {;}
undefined

> {;;}
undefined

> {;;;;;}
undefined

Okay, beautiful, so an empty code block resolves to undefined. Right?

Not exactly!

> var emptyBlock = {;}
Uncaught SyntaxError: Unexpected token ';'

?! Now it is unclear whether the empty code block actually returns undefined, or something else entirely is at play. If it merely did evaluate to undefined, we would expect the above assignment to work.

Does anyone know why this is happening?


Solution

  • Eventually, I figured out how to specify that I want an empty code block, not an empty object.

    This is largely determined by what is before the {, not after it.

    Since you have an = before it, you are in a context where { is the start of an object literal. A ; is not allowed where a property name is expected, so the code errors.

    You can't assign blocks. They aren't values, they are parts of the code structure.

    Both of these seem demonstrably false. var codeBlockValue = {1;2;3}; for example works perfectly fine, and sets codeBlockValue to 3

    No, it doesn't:

    var codeBlockValue = {1;2;3};