1

I was messing around with an AST tree parser and I saw that a ReturnStatement can have multiple expressions. As you can see in the following snippet there are multiple values after the return statement and yet the code get compiled and run successfully (its the last value that gets returned).

function test() {
  return 1, 2, 3;
}

console.log(test());

AST Form:

{
    "type": "ReturnStatement",
    "start": 13,
    "end": 24,
    "argument": {
        "type": "SequenceExpression",
        "start": 20,
        "end": 23,
        "expressions": [{
            "type": "Literal",
            "start": 27,
            "end": 28,
            "value": 1,
            "raw": "1"
        }, {
            "type": "Literal",
            "start": 30,
            "end": 31,
            "value": 2,
            "raw": "2"
        }, {
            "type": "Literal",
            "start": 33,
            "end": 34,
            "value": 2,
            "raw": "3"
        }]
    }
}

What is the point of this feature and/or bug?
When would you ever want to use this syntax?

nick zoum
  • 6,639
  • 5
  • 26
  • 63
  • You could use this syntax on reduce, for example, like this: https://jsfiddle.net/xat107mc/ . Only the last value is returned, like in many other languages. – briosheje Aug 05 '19 at 12:11

1 Answers1

5

1, 2, 3 is not multiple expressions, it's a single expression with the comma operator, which is called SequenceExpression in your AST. The comma only makes sense when subexpressions have side effects. For example, some people love to write reduce callbacks like this:

let count = ary => ary.reduce(function (o, x) { 
    return o[x] = ++o[x] || 1, o 
}, {})

Here, the comma is used here to execute a side effect o[x] = ... and then return the accumulator.

The comma operator is mostly for brevity, you can always get along without it:

let count = ary => ary.reduce(function (o, x) { 
    o[x] = ++o[x] || 1; 
    return o 
}, {})
georg
  • 195,833
  • 46
  • 263
  • 351
  • Just a side note worth to mention, since OP mentions that _What is the point of this feature and/or bug?_, it's actually worth to say that it's like this in many other programming languages. – briosheje Aug 05 '19 at 12:17
  • So the only benefit is to minimize the code? Also I said `multiple expressions` because `AST` called them `expressions` (updated my question). – nick zoum Aug 05 '19 at 12:19
  • @briosheje: according to wiki, the comma operator is only present in C and derivatives and Perl - I won't call it "many others". – georg Aug 05 '19 at 12:29
  • @georg well, may I argue that "C and derivates" is quite a big piece of the whole cake? :P In any case, you're right, indeed, just wanted to mention that it's really not a "bug" and that it's actually available in.. let's say other languages? – briosheje Aug 05 '19 at 12:31
  • Talking about *brevity* but using explicit `return` ... ;) – Jonas Wilms Aug 05 '19 at 12:37