× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Introducing JavaScript 6 - Arrow Functions

In this article we will introduce Arrow Functions, a new resource included in ES6 to simplify the creation of JavaScript functions.

Motivation

Arrow Functions are simplified versions of traditional JavaScript functions. There are two reasons for using Arrow Functions. First, they are shorter to write and handy, especially when creating short functions with couple of lines of code. Finally, they help with the this keyword because it not binds its own.

Step 1: The Arrow Function syntax

In order to create Arrow Functions we must use the new arrow operator =>. The left side of the arrow operator represents the input parameters and the right side represents the actions you want the function to take. We leave off the function and return keywords. The general representation is as follows:

(parameter [, parameter]) => { action }

Let’s start with a traditional function, use an Arrow Function to represent the same behavior and observe what is the difference between these two approaches. This function takes a name as a parameter and creates a greeting to be placed in the div content. The HTML and JavaScript code follows:

<!DOCTYPE html>
<html>
    <head>
        <title>Arrow Functions</title>
    </head>
    <body>
        <h2>Experimenting with Arrow Functions</h2>
        <div id="result"></div>
        <script src="script.js"></script>
    </body>
</html>
'use strict';

function sayGreeting(name) {
    var content = document.getElementById("result");
    content.innerHTML = "Hello, " + name + "!";
}

sayGreeting.("world");

Now, let's adjust our code to use arrow expression. We are putting together three pieces: the input parameter, operator, and the action the function is taking:

let greeting = (name) => "Hello, " + name + "!";
console.log(greeting("world"));

First, we are declaring the greeting variable. If the let keyword is weird to you, it is a nice time to visit our previous article here. On the right side, we have the input parameter (name), the arrow operator and the action joining text with name. It is as if the arrow operator is saying “give me the input parameter(s) and tell me what actions you want me to take”. If there is only one input parameter, as it is the case here, the parenthesis around the parameter are optional. If the function takes no parameters, you use empty parentheses, as in () => “Hello, world!”. The second line prints the results of the call in the console.

> Hello, tester

If you have more than one statement on the right side of the arrow operator, you must use curly brackets {} around them.

Step 2: The impact on the this keyword

Another item that is important with Arrow Functions is the impact on the keyword this. Let’s take an example to illustrate the concept. Here is the HTML with some divs where we will be logging the content of the this keyword in diferent contexts starting with a function, then a function inside an object and finally an Arrow Function inside an object.

<!DOCTYPE html>
<html>
    <head>
        <title>Arrow Functions</title>
    </head>
    <body>
        <h2>Experimenting with Arrow Functions</h2>
        <div id="result1"></div>
        <div id="result2"></div>
        <div id="result3"></div>
        <script src="script.js"></script>
    </body>
</html>

Now, let’s look at the JavaScript code.

function testThis() {
    var content = document.getElementById("result1");
    content.innerHTML = this;
}

testThis();

var course = {
    register: function() {
        var result2 = document.getElementById("result2");
        result2.innerHTML = this;
    }
};

course.register();

var anotherCourse = function() {
    register: () => {
        var result3 = document.getElementById("result3");
        result3.innerHTML = this;
    }
};

anotherCourse.register();

The output will be as follows. Notice that I am using Plunker with Firefox, so if you are using a different browser the result might be slightly different.

[object Window]
[object Object]
[object Window]

In the first call, testThis() is called globally, and the result shows the Window object. However, it is interestingly different when calling the register() function on the course objects. In the first case, it is a regular function, and this represents the context of the object type. In the second call to register(), however, we are using Arrow Functions. Notice that in this scenario, you get the context of the code that is running, which is the Window object. This is important to keep in mind when using Arrow Functions.

In this article, we learned about Arrow Functions. As we have discussed, these are the shorthand representation of functions. They are usually used when the function is short, few lines of code. We also discussed the impact of using the Arrow Functions on this. Try to experiment with the code we discussed above and adjust your personal code to support Arrow Functions.



Senior Software Engineer with experience in C#, JavaScript, jQuery, Knockout JS, Kendo UI, HTML5, and SQL Server. Ayad has more than 20 years experience in technical training and teaching. Contributor to MrBool for about 7 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login