Wednesday, September 9, 2015

Arrow Functions - New in Node 4.0.0

New! Improved! Skipping Numbers!
In news much more important than whatever my frogs did today, Node 4.0.0 was just released. If you're confused by that version number, you're in good company. I thought we were just on version 0.12.7. Did 1.x.x through 3.x.x end up in the same place as Windows 9?

No, no. Node 4.0.0 represents the merge of the Node and Io.js baselines. Io.js split off Node back in December but the two projects have settled their differences and come back together. This means Node now has support for a bunch of new features from the JavaScript ECMA-262 specification, like promises and arrow functions.

I've talked about promises before, but arrow functions...those are interesting. They are basically an even shorter way of expressing anonymous functions.

Consider this example. Let's say you had an array of the first 10 prime numbers and you wanted to add them all up. In a prior version of Node, you could reduce the array by supplying a simple anonymous function as the argument to reduce.

var arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];

var sum = arr.reduce(function(a, b) {
    return a + b;

Not bad. I'm sure we've all done simple anonymous functions like that before. But with an arrow function, the same process looks like this:

var arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];

var sum = arr.reduce((a, b) => a + b);

A bit shorter, and it looks nicer as a single line. So what does that syntax really mean?

The arrow function notation basically says execute one or more statements on the right side of the arrow using one or more arguments from the left side of the arrow. If there is only one statement, the return is implicit (above, the statement a + b is equivalent to return a + b). The arrow, of course, is just an equals sign followed by a greater-than sign. It's really just a more concise way of expressing a function which you may find appealing in certain situations.

// multiple args, one statement
var f = (a, b, c) => c ? a + b : a * b;
f(3, 6, false); // equals 18
f(3, 6, true);  // equals 9

// one arg, multiple statements
var g = a => { var b = a * a; var c = a / 2; return b + c };
g(44); // equals 1958
g(22); // equals 495

Nice, huh? There's a lot more new with Node 4.0.0 as well, so you might want to check it out. I'll probably be migrating to it within the next few weeks. I expect a painless transition, but we'll see. In the mean time, continue to enjoy the comics served up by a prior version of Node. comic for 9 September 2015

No comments:

Post a Comment