Shorthand Functions
JavaScript 1.8 [21] introduces a shorthand (called “expression closures”)
for writing simple functions. If a function evaluates a single
expression and returns its value, you can omit the return keyword and also the curly braces
around the function body, and simply place the expression to be
evaluated immediately after the argument list. Here are some
examples:
letsucc=function(x)x+1,yes=function()true,no=function()false;
This is simply a convenience: functions defined in this way
behave exactly like functions defined with curly braces and the
return keyword. This shorthand
syntax is particularly convenient when passing functions to other
functions, however. For example:
// Sort an array in reverse numerical orderdata.sort(function(a,b)b-a);// Define a function that returns the sum of the squares of an array of dataletsumOfSquares=function(data)Array.reduce(Array.map(data,function(x)x*x),function(x,y)x+y);
[21] Rhino does not implement this feature at the time of this writing.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access