It's happened. It's finally happened. Short function syntax is here! At least, if you're running the nightly version of Firefox (which I am now, due to my promise to adopt the first browser to introduce short function syntax).
Short function syntax replaces the lengthy function
keyword with a symbol =>
, and the almost-as-lengthy return
keyword with the much shorter nothing (for one-liners).
However, this change represents far more than a few saved keystrokes: it marks the beginning of JavaScript as a serious functional programming language.
Let's have a look at it in action. Fire up your Firefox nightly and open up the console. Defining a function can now be done like so:
var cube = x => x * x * x; cube(3); // 27
Very snazzy hey? Where it really shines in as part of the collection manipulation methods: map, reduce, filter, some, every
.
[1, 2, 3, 4, 5].filter(x => x % 2).map(x => Math.sin(x));
In this example we filter on odd numbers (keeping 1,3,5) and then pass them to the Math.sin
function. If we were to write this with normal anonymous functions we'd have this horizontally-scrolling version:
[1, 2, 3, 4, 5].filter(function(x){ return x % 2; }).map(function(x) { return Math.sin(x); });
Which gives us the same result, but buries the actual processing logic in redundant keyword cruft. And that's why this seemingly simply feature is so important - it helps us to clarify and highlight the business logic and intention. Whereas previously it felt as if we were "bending" the language to code in a functional style, the new lambda format formalises it and gives us the thumbs-up to go functional.
It's quite beautiful when you need the one-liners with a single parameter like above - but of course, that's not always the case. If you have multiple parameters, you need to wrap them in parentheses:
[2, 2, 2, 2, 2].map((el, i) => el * i); // [0, 2, 4, 6, 8]
If you have zero parameters, you need an empty parameter list:
[1, 2, 3, "a", "b", "c"].map(() => "hi!"); // ["hi!", "hi!", "hi!", "hi!", "hi!", "hi!"]
Finally, if you want the body of the function to be a block, you need curlies and - unfortunately - an explicit return statement:
[2, 2, 2].map((el, i) => { var double = el * 2; return double * i; }); // [0, 4, 8]
It's a bit sad we don't have implicit returns for blocks, but hey - a few hours ago we didn't even have short-function syntax, so I'm not going to complain about it (just yet). Hopefully once everyone gets a taste for the power of terse cruft-free syntax we can go even further. For now, I'm off to check out my new browser. Oooh, shiny...