Have blocks return the last statement with the Comma Operator
Meghan (she/her)

Meghan (she/her) @nektro

About: 24. Local trans witch who prefers to do magic with a keyboard. she/her. Currently hacking away at making the Web less centralized.

Location:
Massachusetts, USA
Joined:
Mar 13, 2017

Have blocks return the last statement with the Comma Operator

Publish Date: Mar 30 '18
16 6

Some languages allow for a syntax that allows for the last statement to be automatically be returned by the block.

{ 
  System.print("one")
  System.print("two")
  System.print("three")
  2 + 4
}
Enter fullscreen mode Exit fullscreen mode

We can achieve this in JavaScript with the comma operator.

const doSomethings = () => (
    console.log(location.href),
    global.variable += 4,
    12 / 2
);
Enter fullscreen mode Exit fullscreen mode

And just like that, the two code blocks from above would return the same thing!

Comments 6 total

  • Shahriar Siraj Snigdho
    Shahriar Siraj SnigdhoApr 1, 2018

    I don't know about others, but I think that returning with this method is less readable

    • Ben Sinclair
      Ben SinclairApr 1, 2018

      I agree. It's interesting that you can do it, but I prefer to be a little more explicit.

      • Shahriar Siraj Snigdho
        Shahriar Siraj SnigdhoApr 1, 2018

        Since I came from c# background, so returning with comma operator hurts my eyes. No offense, btw!

  • JavaScript Joel
    JavaScript JoelApr 4, 2018

    I use the comma operator often in functional projects for this exact reason and I find it more intuitive than having a return statement.

    One reason is that it mimics the pipe operator that I am frequently using, so the code blocks look similar.

    Also every function flows through from top to bottom and always returning the last value, so in this codebase it becomes very intuitive.

    • Meghan (she/her)
      Meghan (she/her)Apr 4, 2018

      Nice! Speaking of the pipe operator, have you seen github.com/tc39/proposal-pipeline-...

      • JavaScript Joel
        JavaScript JoelApr 4, 2018

        Yes and I am very excited for it. Also excited for the partial application proposal. I think the pipeline proposal would replace compose and pipe and the partial application proposal would replace the need for most currying.

        Very excited!

Add comment