Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

An Introduction to JavaScript/ES6 Arrow Functions

DZone's Guide to

An Introduction to JavaScript/ES6 Arrow Functions

In this post, we take a quick look at how developers can work with arrow functions in their JavaScript-based code.

· Web Dev Zone ·
Free Resource

A true open source, API-first CMS — giving you the power to think outside the webpage. Try it for free.

Arrow Function

Arrow Functions help programmers to write declarative code with JavaScript. While everyone may have different feelings about this addition to Javascript/ES6, whatever camp you belong to you, you will have to deal with variations of Arrow Functions.

Why Do You Need to Know This?

Theoretically, you don't need to learn to use arrow functions at all. You can do everything with good old "function" that you have been doing since you started writing JavaScript code. It could be advantageous in some cases, but you can get away without using them. But even if you don't use it right now, you might end up using arrow functions in the future or you might have to maintain code that was written by someone who loved using arrow functions. 

So there is always wisdom in learning, as knowledge is power!

Now, without spending more time in the introduction, we will get to it and talk about the various ways to use arrow functions.

No Parameters

() => 7

This is the variation where you don't have any parameters for the arrow function — just an expression. For the sake of simplicity, I have avoided using any expression because it could be anything. 

For example: 

var fn = () => 7
// To run: fn()
// expected output: 7  

Single Parameter

p => p*p OR (p) => p*p

With a single parameter, you can either choose to use parentheses or omit them. I personally like using parentheses for consistency. 

For example: 

var fn = (p) => p * p
// To run: fn(5)
// expected output: 25  

Multiple Parameters

(p1, p2) => p1+p2

You have to use parentheses with multiple parameters. 

For example: 

var fn = (p) => p * p
// To run: fn(5)
// expected output: 25  

Using the Gather Operator or REST Parameters

(...p) => expression

Here REST parameters will collect all arguments into an array and provide them to us for processing. When should you use them in your function definition? Simple, when you want to provide flexibility or a variable number of arguments during a function call. Example:

var fn = (...p) =>  p.map(Math.sqrt);
// To run: fn(25, 16)
// expected output: [5, 4]

Using Curly Brackets for a Concise Function Body

(...p) => expression

Now the expression(s) that we use to write the body of an arrow function is called a concise function body. If you want to wrap your logic in curly brackets then you need to remember to use the return keyword. When you don't use curly brackets, the return statement is implicit, whether it is one expression or more.

Example:

var fn = (p1, p2) =>  { return p1 * p2; }
// To run: fn(5, 6)
// expected output: 30

I personally like using a semi-colon at the end of the expression, though it is not necessary (but it won't give you any errors if you use one). Another example:

var fn = (...params) =>  {
	let output = 0;
	for(let param of params) output += param;
	return output;
}
// Usage: fn(1,2,3)
// expected output: 6
// Using with spread operator
let input = [1, 2, 3, 6];
fn(...input)
// output: 12

Returning Object

(p1, p2) => ({"param1": p1, "param2": p2})

To return an object while not using curly brackets you must use parentheses. 

For example: 

// Wrong usage: results in Javascript syntax error
let fn = (p1, p2) => {"param1": p1, "param2": p2}
// Correct usage
let fn = (p1, p2) => ({"param1": p1, "param2": p2})
// To run: fn(10, 20)
// expected output: {"param1": 100, "param2": 200}  

What You Can't Do With Arrow Functions

While you can use all expressions and loops, you can't use "if..else" or "try...catch" inside the concise body of the arrow function, so keep that in mind. If you use these syntaxes, the function will result in a syntax error.

In the End;

A majority of the time arrow functions are used as an argument of another function. It won't have the "var fn =" in front of it. I did this to provide code that we can run in a browser console to test. There are positives of using arrow functions, can learn more about in this article by Tim Fogarty. They are anonymous by definition and, in addition to the above article, I would like to add a few more definitions:

  • They are anonymous and so will show up as anonymous functions in stack trace. You can store them in a variable (like we did in all examples above) and it will use the name of the inference.
  • You can't easily self-reference to it (think about recursion).

Credits/References

This post is compiled to keep a quick reference for variations of arrow functions. It is compiled from learnings from a course by Kyle Simpson, ES6: The Right Parts.

Feel free to shout out your experience with new features of ES6 and your thoughts on arrow functions in the comments below.

The New Standard for a Hybrid CMS: GraphQL Support, Scripting as a Service, SPA Support. Watch on-demand now.

Topics:
web dev ,javascript tutorial ,arrow functions ,javascript tutorial for beginners

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}