statements that could be expressions?

Mike Samuel mikesamuel at
Wed Jun 1 17:16:42 PDT 2011

2011/6/1 Peter Michaux <petermichaux at>:
> Could some of JavaScript's statements also be allowed as expressions?
> In Perl there is the common idiom when opening a file
>  open F, "< $f" or die "Can't open $f : $!";
> In JavaScript could "throw" be an expression?
>  f() || throw 'f failed';
> Could JavaScript's "if" become an expression? (I know JavaScript the
> ?: operator but this is just a for example.)
> Could a Block statement also be an expression like Scheme's "begin"?

The semantics of all of these are specified in terms of expression
semantics.  Every statement or expression is specified in terms of a
triple of (one of (normal, throw, break, continue), value, label).
This is how eval can take a Program production and return a value or
propagate an exception.  So it *could* be done without changing the
semantics of many statements.

With existing code, it can already happen in some cases.

A block of statements that can be translated to expressions can
already be turned into an expression using the comma operator.

conditionals can translate to && and ?: operators.

Throw and return can currently be factored left so
    { foo(); if (bar()) baz(); return boo(); }
is equivalent to
    return (foo(), bar() && baz(); boo());
and a number of code minifiers take advantage of this

Throw statements whose exception is reliably an Error instance can be
factored to an expression via library code
    Error.prototype.raise = function () { throw this; };
or a well known global function that can throw any value.

Loops whose initializers and bodies can be translated to expressions
can be translated to expressions using eval(...).

That basically leaves try/catch, break, return, continue, labeled
loops or loops with declarations, and declarations themselves as the
sticky points.

> Peter
> _______________________________________________
> es-discuss mailing list
> es-discuss at

More information about the es-discuss mailing list