Returning a value without an explicit return statement

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

At least it has been so far, but it looks like ECMAScript 6, at least sometimes, allows you to omit return .

In what circumstances will this be so? Will this be due to the difference between function and => or is there some other criterion?

+4
source share
1 answer

The final material on this is the latest draft of the ES Harmony specification and, in particular, the part derived from the arrow syntax proposal . For convenience, an unofficial version of HTML can be found here .

In short, this new syntax will more clearly describe the definition of functions. The ES spec project has all the details, I will explain very rudely here.

Syntax

 ArrowParameters => ConciseBody 

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

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

The ConciseBody part defines the function body. It can be defined either as it has always been defined, for example.

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

or, in a special case, when a function returns the result of evaluating a single expression, for example:

 theExpression 

If that sounds pretty abstract, here is a concrete example. All of these function definitions will be identical in the current project specification:

 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 powerful syntax that C # uses to enable the definition of lambda functions.

+5
source

Source: https://habr.com/ru/post/1484176/


All Articles