DEV Community

Cover image for JavaScript Arrow Functions
Dev-Coder
Dev-Coder

Posted on

JavaScript Arrow Functions

_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:

Alt Text

Arrow Function Example

Alt Text

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:

Alt Text

The typeof operator returns function indicating the type of arrow function.

Alt Text


Arrow Functions With Multiple Parameters

If an arrow function has two or more parameters, we need to use the following syntax:

Alt Text

For example, To sort an array of numbers in the descending order, we use the sort() method of the array object as follows:

Alt Text

The code is more concise with the arrow function syntax:

Alt Text


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.

Alt Text


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:

Alt Text

However, the following code works perfectly fine:

Alt Text

JavaScript allows us to use the line break between parameters as shown in the following example:

Alt Text


Summary:

Arrow functions are handy for one-liners. They come in two flavors:

  1. Without curly braces: (...args) => expression – the right side is an expression: the function evaluates it and returns the result.
  2. With curly braces: (...args) => { body } – brackets allow us to write multiple statements inside the function, but we need an explicit return to return something.

Oldest comments (0)