Understanding JavaScript Arrow Functions

Understanding JavaScript Arrow Functions

Are you new to JavaScript, and wondering what the arrow functions are? Have you see a bunch of arrows all across your team’s codebase and unsure what they really do? Well, you have reached the right spot to learn about arrow functions.

Originally published at https://programmingwithmosh.com

Arrow functions were introduced in the ES6 standards of JavaScript a few years ago. It instantly became a hit, and everyone started using it. Arrow functions help in writing concise functions.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the thisargumentssuper, or new.target keywords.

Let’s take a look at some examples to learn and understand arrow functions in JavaScript.

Motivation and Benefits

So why did JavaScript need the arrow function in the first place.

1. Concise and shorter syntax

Let’s look at an example using regular functions without the arrow functions.

// Regular function without arrow
function myFunction (a) {
return (a * 5);
}
// Call function
myFunction(10)
//50

Simple enough right. Noe let’s use the arrow functions instead and see how it looks.

var myFunction = (a) => a * 5
// Call function
myFunction(10)
//50

Much shorter. This is one of the main motivations behind introducing the arrow function. It lets you write shorter and more concise code.

2. No separate this binding

Before the introduction of the arrow functions, the concept of this was very confusing in JavaScript. The arrow function helps in reducing the confusion around the this keyword. In arrow functions the this is not bound explicitly. Instead it is lexically bound. Let’s look at an example to understands what this means.

The Mozilla developer’s guide has a good example on arrow functions. In the example below, we have a function Person() with an age parameter. We are going to increment the age in regular intervals of time, in the growUp() function. This function is passed as a parameter to the JavaScript setInterval() function. Until the use of arrow function, every function defined its own this value based on how it is called.

function Person() {
 var that = this;
  that.age = 0;
 
  setInterval(function growUp() {
    // The callback refers to the `that` variable of which
    // the value is the expected object.
    that.age++;
  }, 1000);
}

Now if we were to replace this example with the ES6 arrow function instead, here is what happens. The arrow function does not have its own this. The this value of the enclosing lexical scope is used. So while searching for this which is not present in current scope they end up finding this from its enclosing scope. This makes the code a lot more readable and concise. Take a look at how the code is re-written with the use of arrow function.

But, what is lexical scope?

Lexical scoping in JavaScript uses the location where a variable is declared within the source code to determine where that variable is available (Scope of that variable)
function Person(){
  this.age = 0;
 
  setInterval(() => {
    this.age++; // |this| properly refers to the Person object
  }, 1000);
}
 
var p = new Person();

Notice here that the setInterval() takes in an anonymous arrow function as the parameter.

Arrow Functions and its syntax

Alright, let’s dive into some more examples to understand arrow functions better.

Single Parameter

You can pass a single parameter to your arrow function as follows. The parenthesis here is optional.

var myFunction = (a) => a + 10
// alternate without parentheses
var myFunction = a => a + 10

Multiple Parameters

Just like any other function, arrow functions can take multiple parameters as arguments. Since we are passing more than one parameter, the parentheses are required here.

var myFunction = (a, b) => a + b 

No Parameters

You can also write arrow functions without any parameters as follows.

var myFunction = () => 5 + 10 

Function Body

Arrow functions can either have the shorter concise body, without any braces or it can also have the regular block body like regular functions. Note here that, if the block body with braces are used, then the function needs an explicit return statement. This is not necessary in the “short” syntax.

// concise body syntax, implied "return"
var myFunction = a => a * 5            
 
// with block body, explicit "return" needed
var func = (a) => {
 return a * 5;
}

Line Breaks

When you are using arrow functions, be cautious about the way you structure your line breaks. Sometimes it may result in a syntax error.

var myFunction = (a, b)
=> a+5
// SyntaxError: expected expression, got '=>'

In the example above, when the arrow is placed on another line without a parenthesis, it returns a syntax error.

var func = (
  a,
  b
) => (
  a + 5
);
// no SyntaxError thrown

Whereas, this code snippet doesn’t return a syntax error with the line breaks.

Drawbacks of Arrow Functions

Well, everything has pros and cons. Let’s look at some problems you may face with the arrow functions.

Debugging may not be easy

Arrow functions are anonymous (the function as no name). This means, when you run into issues, it may be harder to debug the root cause. If the functions have names, it is easier to trace back to the problem. With anonymous functions, it adds a level of complexity to debugging.

Readability takes a hit

Although, arrow functions help in writing short and concise code, it is not necessarily readable. Most programmers are used to the traditional way of writing functions, and arrow functions changes this completely. This makes code harder to read and might take a while for someone newer to get the grasp of the code.

Conclusion

Arrow functions are fun to use. They make you write shorter, concise code. But they may also be harder to debug sometimes. There is more than what we covered in this blog post on Arrow functions. But we have covered the basics to get you started. I hope you enjoyed this post. Please share the post or leave a comment if you enjoyed the post. 

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

JavaScript Basics Before You Learn React

Build a CMS with Laravel and Vue

Google’s Go Essentials For Node.js / JavaScript Developers

7 best JavaScript Design Patterns You Should Know

12 Concepts That Will Level Up Your JavaScript Skills

javascript es6 function

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

JavaScript: The Good Parts of Arrow Functions

JavaScript: The Good Parts of Arrow Functions. You might not know this one major difference between normal functions and ES6 arrow functions in JavaScript.

JavaScript = Arrow Functions => ES6

Basic Syntax Explained for Beginners. Arrow function (also known as “fat arrow; =>” function) was introduced in ECMAScript 2015 as a new syntax for declaring functions. JavaScript = Arrow Functions => ES6

How “this” binds in regular functions and arrow functions in JavaScript

Arrow syntax automatically binds this to the surrounding code’s context…but what does this mean? Let me explain what does that even means! For that, we must first understand what was the problem that can be solved using arrow functions. Let us talk about the scenario where we use a normal function instead of an arrow function.

How to Declare a JavaScript Function with the New ES6 Syntax

How do you know which arrow function syntax to use? In this Arrow Function JavaScript tutorial, you'll learn How to declare a JavaScript function with the new ES6 syntax. Learn how to declare an arrow function.

JavaScript Tutorial - ES6 Arrow Functions

In this JavaScript Tutorial, I give a tutorial on ES6 arrow functions. I will explain how to write on by converting a regular named function or anonymous function to use the new arrow function syntax. This will cover a whole variety of examples and how to convert them to simplify your JavaScript code.