DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Operator Overloading in Java
  • Reactive Programming
  • How To Manage Vulnerabilities in Modern Cloud-Native Applications
  • What Is Istio Service Mesh?

Trending

  • Operator Overloading in Java
  • Reactive Programming
  • How To Manage Vulnerabilities in Modern Cloud-Native Applications
  • What Is Istio Service Mesh?
  1. DZone
  2. Coding
  3. Languages
  4. An Introduction to JavaScript/ES6 Arrow Functions

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.

Dharmavirsinh Jhala user avatar by
Dharmavirsinh Jhala
·
Mar. 15, 19 · Tutorial
Like (13)
Save
Tweet
Share
10.97K Views

Join the DZone community and get the full member experience.

Join 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.

Bracket (tournament) code style REST JavaScript Object (computer science) Web Protocols Console (video game CLI) Testing Programmer (hardware) Operator (extension)

Published at DZone with permission of Dharmavirsinh Jhala. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Operator Overloading in Java
  • Reactive Programming
  • How To Manage Vulnerabilities in Modern Cloud-Native Applications
  • What Is Istio Service Mesh?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: