_Today, We will learn how to use the JavaScript arrow function to write more concise code for function expressions.
Introduction
ES6 arrow functions provide you with an alternative way to write a shorter syntax compared to the function expression.
The following example defines a function expression that adds two numbers:
Arrow Function Example
In above example, The arrow function has one expression x + y so it returns the result of the expression.
However, if you use the block syntax, you need to specify the return keyword:
The typeof operator returns function indicating the type of arrow function.
Arrow Functions With Multiple Parameters
If an arrow function has two or more parameters, we need to use the following syntax:
For example, To sort an array of numbers in the descending order, we use the sort() method of the array object as follows:
The code is more concise with the arrow function syntax:
Arrow Functions With Single Parameter
- If an arrow function takes a single parameter, we can use the following syntax:
(parameter1) => { statements }
- Note that, We can omit the parentheses as follows:
parameter => { statements }
The following example uses an arrow function as an argument of the map() method that transforms an array of strings into an array of the string’s lengths.
Arrow Functions With No Parameter
If the arrow function has no parameter, we must use the parentheses, like this:
( ) => { statements }
Line Break Between Parameter Definition and Arrow
JavaScript doesn’t allow us to use a line break between the parameter definition and the arrow ( => ) in an arrow function. The following code produces a SyntaxError:
However, the following code works perfectly fine:
JavaScript allows us to use the line break between parameters as shown in the following example:
Summary:
Arrow functions are handy for one-liners. They come in two flavors:
- Without curly braces: (...args) => expression – the right side is an expression: the function evaluates it and returns the result.
- With curly braces: (...args) => { body } – brackets allow us to write multiple statements inside the function, but we need an explicit return to return something.
Top comments (0)