This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
Arrow functions are a new ES6 syntax for writing JavaScript functions. They will save developers time and simplify function scope. Surveys show they are the most popular ES6 feature:
Source: Axel Rauschmayer survey on favorite ES6 features
Source: Ponyfoo’s survey on the most commonly used ES6 features
The good news is that many major modern browsers support the use of arrow functions.
[author_more]
This post will cover the details of Arrow functions, specifically, how to use them, common syntaxes, common use cases, and gotchas/pitfalls.
What Are Arrow Functions?
Arrow functions – also called "fat arrow" functions, from CoffeeScript (a transcompiled language) are a more concise syntax for writing function expressions. They utilize a new token, =>
, that looks like a fat arrow. Arrow functions are anonymous and change the way this
binds in functions.
Arrow functions make our code more concise, and simplify function scoping and the this
keyword. They are one-line mini functions which work much like Lambdas in other languages like C# or Python. (See also lambdas in JavaScript). By using arrow function we avoid having to type the function
keyword, return
keyword (it’s implicit in arrow functions), and curly brackets.
Using Arrow Functions
There are a variety of syntaxes available in arrow functions. EcmaScript.org has a thorough list of the syntaxes and so does MDN. We’ll cover the common ones here to get you started.
Let’s compare how ES5 code with function expressions can now be written in ES6 using arrow functions.
Basic Syntax with Multiple Parameters (from MDN)
Code Example: http://ift.tt/1SUGvG8
The arrow function example above allows a developer to accomplish the same result with fewer lines of code and approximately half of the typing.
Curly brackets are not required if only one expression is present. The preceding example could also be written as:
var multiply = (x, y) => x*y;
Basic Syntax with One Parameter
Parentheses are optional when only one parameter is present
No Parameters
Parentheses are required when no parameters are present.
Code Example: http://ift.tt/1PNI6XR
Object Literal Syntax
Arrow functions, like function expressions, can be used to return an object literal expression. The only caveat is that the body needs to be wrapped in parentheses, in order to distinguish between a block and an object (both of which use curly brackets).
Code example: http://ift.tt/1PNI7e5
Use Cases for Arrow Functions
Now that we’ve covered the basic syntaxes, let’s get into how arrow functions are used.
One common use case for arrow functions is array manipulations and the like. It’s common that you’ll need to map or reduce an array. Take this simple array of objects:
Continue reading %ES6 Arrow Functions: The New Fat & Concise Syntax in JavaScript%
by Kyle Pennell via SitePoint
No comments:
Post a Comment