Telerik blogs
JavaScriptT2 Light_1200x303

Learn more about one of the most powerful features of ES6: arrow functions. We'll learn how we can have better, more concise, and more powerful functions in JavaScript. 

In this article, we’re going to learn more about one of the best ways to declare and create functions in JavaScript. Introduced in the ES6 version of JavaScript and called arrow functions, it’s a way that we can create better functions with a cleaner syntax, making our code more readable. We’re going to learn about arrow functions, how and when to use them instead of the standard function declaration way — but first let’s learn more about functions and how they work in JavaScript.

One of the most special and important parts of programming, in general, is functions, the way we can use a simple piece of code to execute a particular task. This is especially so in JavaScript. Almost everything in JavaScript happens inside a function.

The most important lines of code of your application right now might be inside a function. All the user’s logic, the authentication logic, and pretty much everything important is done by functions. A function is a block of code that can execute some task, and we can pass parameters to it, and it is only executed when it’s called.

In JavaScript specifically, functions are objects, and they should always return a value, otherwise, they’ll return undefined to us. Let’s learn a little bit more about functions in JavaScript, and then we’re going to understand why arrow functions are such a powerful and beautiful way to create functions in JavaScript.

Functions in JavaScript

In JavaScript, functions are objects, but they’re a special type of object called function objects. We can work with functions as we want — we can assign them to a variable, we can use them as an object property, we can pass a function to an array or use one as an array element, etc.

The most common way to create a function, and the way that we used a lot to create our functions before the ES6 release (the version of ECMAScript that launched in June 2015) was by using a function keyword, then the name of the function, followed by parentheses (). Inside those parentheses you can have one or many more parameters as you want, a pair of curly braces, and, finally, inside of it, you put your code to execute it.

Before the ES6 release, and even until now, a lot of developers still write their functions this way:

    function myName() {
      console.log("Hello Leonardo");
    }

    myName() // Hello Leonardo

Inside the parentheses () you can have one or more parameters as you want to. For example, if we want our function to print a hello message with our name, all we need to do is pass a name parameter to our function, like this:

    function myName(name) {
      console.log(`Hello ${name}`);
    }

    myName("Rodrigo") // Hello Rodrigo

We used a template literal, another feature released with ES6, that allows us to embed expressions in JavaScript strings.

When you create a new function on your application, the current scope creates a new variable identifying as the function name. This specific variable holds the function object, and then we can call it anywhere and whenever we want to. This simple function receives a name as a parameter and returns, in our case, a message on the console with the name passed as a parameter.

A nice thing that a lot of developers don't know about related to functions is how to differentiate function declarations and function expressions. Basically, a function declaration is when you use the function keyword, like this:

    // This is a function declaration
    function myName(name) {
     console.log(`Hello ${name`);
    }

And, on the other side, a function expression looks like this:

    // This is a function expression
    const myName = function(name) {
     console.log(`Hello ${name`);
    }

With a function declaration, you define a named function variable without a variable assignment; instead of starting with a var, const or let declaration, you start with a function keyword. A function expression is pretty different — it defines a new function as part of another expression, and most of the time we used a variable for that.

But what exactly are the benefits of it? Basically, when you use a function declaration instead of a function expression, your function will be known before any code is run, allowing you to call a function before you declare. This is called hoisting.

Now that we know a little bit about functions in JavaScript, let's understand why everything has been starting to use arrow functions, why they're so powerful and how they can make our code cleaner.

Arrow Functions

Back in 2015, we had the ES6 release, which was a major enhancement to JavaScript and brought a lot of new features to the language. In that release, we got some major changes, such as:

  1. Constants — Now we can use constants in JavaScript, a new way to create values that can only be defined once per scope.
  2. Template literals — A new way that we can work with strings, allowing us to embed variables and expressions in strings.
  3. Classes — One of the most important parts of object-oriented programming, ES6 also brought us classes and allows us to use them with a modern syntax.

ES6 was a big release and it improved a lot about the JavaScript language and also the community. Somehow it got much easier and more fun to write JavaScript code.

One of the most important changes that this release brought to us was arrow functions. Without a doubt, it’s one of the most popular features of ES6 — we can now create more concise, cleaner, and more readable functions by using the => operator. For example, this is how a simple function would look using the function keyword:

    // This is a simple function
    function myCar(car) {
      console.log(`My car is a ${car}`);
    }

If we use an arrow function to write this function, this is how it would look:

    // This is an arrow function
    const myCar = (car) => {
      console.log(`My car is a ${car}`);
    }

Some differences that we might point out in our arrow function: first, after the name of the function, comes a = operator, then open parentheses (), and inside those parentheses we can have one or more parameters. After the parentheses, we use the => operator, and then do the rest normally. For more concise functions, known as pure functions, we can have an arrow function in only a single line, like this:

    const myCar = (car) => `My car is a ${car}`;

A thing that you should pay attention here is the curly braces. If an arrow function has the curly braces, you'll always need to have the return statement at the end of the function. Another really nice thing about arrow functions is: we can omit the parentheses! If we have a single parameter, we can omit the parentheses, so our function will look like this:

    const myCar = car => `My car is a ${car}`;

Much cleaner, right? And here comes another really nice point about arrow functions: you don't need to bind this anymore. An arrow function lexically binds their context, which means it lexically binds the this, and the this value will always refer to the originating context.

    this.cars.map(car => `This is my car ${car}`);

We still can have anonymous functions by using arrow functions, like this:

    (num1, num2) => num1 + num2;

When Should We Use Arrow Functions?

Although arrow functions are a powerful way to create functions in JavaScript, we must take care and understand how and when to use arrow functions instead of the standard function keyword way. Arrow functions were created to simplify functions, making our scope easier to deal with, and also to lexically bind the this value.

  1. Arrow functions intend to fix the problem where we need to access a property of this inside a callback. But if you're going to deal with the this value, the best way is not to use arrow functions.
  2. Arrow functions don't replace all the functions that you have in your code right now. They can work very well with some simpler and purer functions, but they are not going to work in all cases.
  3. When using object prototypes, classes, or object literals, avoid using arrow functions. They can cause you a bit of a problem because of the this value. Sometimes we might want the this value to refer to something else, but it ends up referring to the window, and it'll be a little hard to debug it.

For code readability and conciseness, arrow functions are the best option. They make your code cleaner and more readable, and, in some cases, you can have a function in just one single line! If you're planning to have a modern application, with more readable and cleaner code, arrow functions might be the best option for you. That doesn't mean that standard function declarations are bad and you should not use them. No! Standard function declarations are a nice way to create functions in JavaScript, a lot of people still prefer to use them instead of arrow functions. It's only a point of view of some developers who don't like arrow functions that much.

Standard functions and arrow functions have some differences, but the main goal when you're creating a functions is always to create the purest function possible. That means that it'll always return the same value. Whether you're using standard functions or arrow functions, that doesn't matter — the point is to write more readable and cleaner code, always.

Conclusion

In this article, we learned about arrow functions in JavaScript, and how we can improve readability and our code in general by using this feature introduced in ES6. We also learned more about functions in general in JavaScript, how we were using functions before the ES6 release, and also learned some differences between the standard functions and arrow functions.


Leonardo Maldonado
About the Author

Leonardo Maldonado

Leonardo is a full-stack developer, working with everything React-related, and loves to write about React and GraphQL to help developers. He also created the 33 JavaScript Concepts.

Comments

Comments are disabled in preview mode.