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:

let succ = 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 order
data.sort(function(a,b) b-a);

// Define a function that returns the sum of the squares of an array of data
let sumOfSquares = 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.

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.