Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active April 16, 2016 12:00

Revisions

  1. DmitrySoshnikov revised this gist Apr 6, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion expression-only.md
    Original file line number Diff line number Diff line change
    @@ -64,7 +64,7 @@ let a = do {
    console.log(`a is ${a}`); // a is 100
    ```

    Or even switch-expression:
    Or even _`switch`-expression_:

    ```js
    let x = 10;
  2. DmitrySoshnikov created this gist Apr 5, 2016.
    87 changes: 87 additions & 0 deletions expression-only.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    ### "Everything is an expression"... since ES1?

    Many languages support _"expression-only"_ semantics, allowing to use any construct in an _expression position_.

    > __NOTE:__ the difference between _expressions_ and _statements_ is that the former produce a value, while the later don't.
    For example, Ruby's _`if`-expression_:

    ```ruby
    x = 10

    a = if x == 10
    100
    elsif x > 10
    200
    else
    300
    end

    puts "a is #{a}" # a is 100
    ```

    JavaScript developers asked for this feature for a long time, however it's not possible to use `if` as an expression..

    _... or is it?_

    In fact, since even earlier versions, ECMAScript supports evaluation of blocks returning the value of the _last evaluated statement_ in it. Which is the exact semantics of such expressions in other languages.

    There is a proposal for _`do`-expressions_ now, though even today, it's possible, and _always was_. However, with the approach described, it is yet impractical since uses `eval` to achieve this.

    Still though, proving the concept:

    ```js
    let x = 10;

    let a = eval(`
    if (x === 10) {
    100;
    } else if (x > 10) {
    200;
    } else {
    300;
    }
    `);

    console.log(`a is ${a}`); // a is 100
    ```

    This directly corresponds to the _`do`-expression_ that brings a bit of a sugar:

    ```js
    let x = 10;

    let a = do {
    if (x == 10) {
    100;
    } else if (x > 10) {
    200;
    } else {
    300;
    }
    };

    console.log(`a is ${a}`); // a is 100
    ```

    Or even switch-expression:

    ```js
    let x = 10;

    let a = eval(`
    switch (x) {
    case 10: 100; break;
    case 20: 200; break;
    default: 300;
    }
    `);

    console.log(a); // 100
    ```

    As we see, there is no any magic here, the feature is and was always [specified](http://www.ecma-international.org/ecma-262/6.0/#sec-block-runtime-semantics-evaluation) by the ES standard. It is very convenient and useful, so we look forward to get _`do`-expressions_ soon.

    Also if you use [Babel](http://babeljs.io/), it already [supports](http://goo.gl/ZNTIH9) it as an experemental plugin.

    Have fun with ES ;)