Arrow functions have been introduced to Javascript as a more concise way to write function expressions.
Here are some examples of the syntax. Instead of this old-style regular function
var multiply = function (x,y) {
return x*y;
}
we can write
var multiply = (x,y) => x*y;
We can drop the function keyword, and if just returning an expression, we can drop the return keyword, too.
If there is only one argument, the parenthesis around the argument is optional:
var square = x => x*x;
square(5); // 25
We do need the parenthesis if there are no arguments to the function:
var logFinished = () => { console.log("Finished"); }
var logFinished = () => { console.log(“Finished”); }
As you saw above, if you have a single line expression, the braces around the function body are optional. However ,if you are returning an object, you’ll need to put parenthesis around the object.
var createPerson = (name, age) => ( {name: name, age: age} );
person = createPerson('Bob', '24'); // Object {name: 'Bob', age: 24}
And, if you are returning a value from a multiline block, you do need to use the return keyword.
var myfunction = (x)=> {
x=x+1;
return x*x;
}
This concise syntax helps a lot when writing a chain of asynchronous callbacks, such as when you are making REST calls to a server. A busy statement like
aAsync().then(function() {
return bAsync();
}).then(function() {
return cAsync();
}).done(function() {
finish();
});
becomes
aASync().then( ()=>bAsync()) ).then( ()=>cAsync() ).done( ()=>finish() );
(I lifted this example from https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/)
Here is a good overview: https://javascript.info/function-expressions-arrows
Note: Arrow functions do not bind the “this” keyword, reducing confusion when you have a bunch of nested functions. When you are ready to dig into arrow function, you’ll find a lot of articles with details and examples of this online.
Arrow functions work now in modern browsers. https://kangax.github.io/compat-table/es6/
This post first appeared on the internal CIT Custom Development blog.