Typescript arrow functions

Author: Dawid Adach

-

Since you already know how to use Named functions and Anonymous functions let me show you another type of function which you will be dealing while building Angular Applications

Let's have a look following sample:

// Named function
function add(x, y) {
    return x + y;
}

// Call named function
console.log(add(5,10));

You can write same using arrow functions (sometimes also called fat arrow functions.:

var add = (x,y) => x+y;
console.log(add(5,10));

As you can see they are not that fat :) They are actually, shorter and less verbose than traditional function expressions. Arrow functions have 2 huge advantages, first one you already know:

1. Shorter syntax:

Arrow functions are always anonymous and turn:

(parameters) { expression }

// Example:
function add(x, y) {
    return x + y;
}

into:

(parameters) => {expression}

// Example:
(x,y) => {x+y};

In case your function doesn't use input parameters, you can use even shorter syntax:

 () => {expression}

// Example:
() => {console.log('Doing some math...'); return 1;}

When you only have one parameter, the opening parenthesis are optional:

parameters => { expression }

// Example:
z => { return z*z}

Finally, if you are returning an expression, you can remove the brackets and return statement:

 () => expression

// Example:
z => z*z; 

2. Handling `this`

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

Arrow functions do not have this, arguments or other special names bound at all - when the object is being created the name this is found in the enclosing scope, not the person object.

Consider following example:

var name = "david";
var person = {
    name: "john",

    shout: function () {
        console.log("my name is ", this.name);
    },
    shout2: () => {
        console.log("my name is ", this.name);
    },
};

person.shout();  // "john"
person.shout2(); // "david"

As you can see, when we are using normal functions this corresponds to the name: john (the closest object), while in case of arrow function, this refers to global scope: david

Why is it important?

Functions always have their own this. But that prevents you from accessing the this of, e.g., a surrounding method from inside a callback:

function Prefixer(prefix) {
    this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) { // (A)
    'use strict';
    return arr.map(function (x) { // (B)
        // Doesn’t work:
        return this.prefix + x; // (C)
    });
};

var pre = new Prefixer('Hi ');
console.log(pre.prefixArray(['Joe', 'Alex']));

This will generate an error:

TypeError: Cannot read property 'prefix' of undefined

This is because, in line C, we’d like to access this.prefix, but can’t, because the this of the function from line B shadows the this of the method from line A. In strict mode, this is undefined in non-method functions, which is why we get an error if we use Prefixer.

There is a workaround which we can use:

function Prefixer(prefix) {
    this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
    var that = this; // (A)
    return arr.map(function (x) {
        return that.prefix + x;
    });
};

var pre = new Prefixer('Hi ');
console.log(pre.prefixArray(['Joe', 'Alex']));

But this is tricky and making code more complex, while using arrow function solves the issue:

function Prefixer(prefix) {
    this.prefix = prefix;
}
Prefixer.prototype.prefixArray = function (arr) {
    return arr.map((x) => {
        return this.prefix + x;
    });
};

var pre = new Prefixer('Hi ');
console.log(pre.prefixArray(['Joe', 'Alex']));

Lesson summary:

Since ES6, you can use arrow functions to make your code less verbose:

//Multiple input parameters => mixed output
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
(param1, param2, …, paramN) => { return expression; }

// Single input (parenthesis are optional)
(singleParam) => { statements }
singleParam => { statements }
singleParam => expression


// Empty list of parameters
() => { statements }

As a disclaimer, there is more to arrow functions than what was explained in this article. But this should give you a great base of knowledge for further learning! As always, leave a comment if you have any great resources on the subject for others to explore.

New tutorials coming soon!

This is the last lesson in this chapter, in next tutorial which will be ready by the end of March'18 , I will show you how to create a real Admin Panel in Angular. If you don't want to miss that - subscribe to my newsletter using form inside the sidebar on the right side of this page. No spam, just content :)


Spread the word:
Do you need help?: Use our support forum

About the author

Dawid Adach
For more than 5 years Dawid worked as an IT Consultant specializing in SOA/EAI/ESB in the banking domain. He gained experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the most prestigious companies. Since co-founding mdbootstrap.com & brandflow.net in 2016 he has been using and teaching technologies such as Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...