Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a value without an explicit return statement

In JavaScript, falling off the end of a function returns undefined; if you want to return a value, you need to use an explicit return statement.

At least this was hitherto the case, but it looks like ECMAScript 6 will at least sometimes allow the return to be omitted.

In what circumstances will this be the case? Will it be related to the distinction between function and => or is there some other criterion?

like image 427
rwallace Avatar asked Jun 03 '13 11:06

rwallace


1 Answers

The definitive material on this subject is the latest ES Harmony specification draft, and specifically the part derived from the arrow function syntax proposal. For convenience, an unofficial HTML version can be found here.

In short, this new syntax will allow the definition of functions much more concisely. The ES spec draft has all the detail, I 'll explain very roughly here.

The syntax is

ArrowParameters => ConciseBody

The ArrowParameters part defines the arguments that the function takes, for example:

()                   // no arguments
arg                  // single argument (special convenience syntax)
(arg)                // single argument
(arg1, arg2, argN)   // multiple arguments

The ConciseBody part defines the body of the function. This can be defined either as it has always been defined, e.g.

{ alert('Hello!'); return 42; }

or, in the special case where the function returns the result of evaluating a single expression, like this:

theExpression

If this sounds rather abstract, here's a concrete example. All of these function definitions would be identical under the current draft spec:

var inc = function(i) { return i + 1; }
var inc = i => i + 1;
var inc = (i) => i + 1;
var inc = i => { return i + 1; };

As an aside, this new syntax is exactly the same great syntax that C# uses to allow the definition of lambda functions.

like image 56
Jon Avatar answered Sep 24 '22 05:09

Jon