Experienced JavaScript programmers take advantage of function expressions, they are used a lot in callbacks, either for DOM access or any other related setup. Another syntax addition to the upcoming ECMAScript 6 is the arrow function expression to let us write a shorter function expression.
A simple way to look at this arrow function notation (section 13.2 in the latest ES6 draft) is as a shorthand form of a normal function expression. This is best illustrated with an example. Say you want to produce the list containing the salary of every employees. By using Array map, it will look like the following snippet:
salaryList = employeeList.map(function (e) { return e.salary; });
Note the function expression as the callback for map()
is rather verbose. With an arrow function expression, that construct can be shortened to:
salaryList = employeeList.map(e => e.salary);
No need for function
and return
. In fact, if you are about to implement the same task with other languages (such as Scala, CoffeeScript, C#), you would end up with a very similar syntax.
How does a syntax tree look like when there is an arrow function? Rather straightforward, no surprise there.
An arrow function expression is designed primary for the case where you need to return a value. However, it still works if you don’t care about returning anything and just want to execute some statements. Take a look at this example:
employeeList.forEach(e => { console.log(e.name); });
Another fun thing with such a shorthand is when you start cascading more functions. For example, if now we are interested in the average salary, this can be computed by:
var total = employeeList.map(e => e.salary).reduce((p, q) => p + q);
var averageSalary = total / employeeList.length;
That’s just way shorter and less crowded compare to function expressions everywhere. It is important to notice that if you have more than one parameter, you need to enclose the parameters with brackets.
Since an arrow function expression is just another form of an assignment expression, we can keep it as a normal object (either for further reuse or just to make it easy to follow), as illustrated in the following fragment (neat, isn’t it?):
var adder = (p, q) => p + q;
var avg = employeeList.map(e => e.salary).reduce(adder) / employeeList.length;
Combine it with array comprehension and magically it does not look to JavaScript-y anymore!
I believe the use of arrow function expression strikes a good balance between readability and expressiveness. What do you think?