Have blocks return the last statement with the Comma Operator

Meghan (she/her) - Mar 30 '18 - - Dev Community

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .