Comments

What are JavaScript Arrow Functions?

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.

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. You can follow me on twitter @AdhithiRavi

If you are looking for the perfect course on JavaScript, look no where else. Mosh has a JavaScript bundle with the best materials to help you learn JavaScript.

https://codewithmosh.com/p/full-stack-javascript-developer-bundle

Check the link above to enroll in the course.

Adhithi Ravichandran is a Senior Software Engineer based in Kansas City. She is currently working on building mobile apps using React Native for critical healthcare scenarios. Adhithi is a regular conference speaker at various tech conferences. Adhithi graduated with a Masters degree in Computer Science from the University of Kansas and has been in the tech industry for over 7 years. She has worked on several technologies over the years, and one of her recent favorite is React Native.
Tags: , , ,

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts