May 6, 2020 · by Cristian Ioan Chiorescu

A Short Introduction into Arrow Functions

Cognizant Softvision Front-End Developer discusses this powerful tool and shares use cases

Have you ever wondered, while debugging, what happened with “this” and why is it that sometimes it isn’t what you expect it to be? As a Front-End Developer at Cognizant Softvision, allow me to bring some “context” into “this.”

Introduction into Arrow Functions

Arrow Functions was introduced with ES6 as a new syntax for writing Javascript functions. This feature is supported by most browsers. 

To understand what Arrow Functions do, we need to take a step back and take a look at “this” context.

The “this” context

The context is the value of the “this” keyword, which, in most cases, is determined by how a function is called (runtime binding)(4). In other words, it is a reference to the object or the function that owns the currently executed code or in which the code is executed. 

In the global context, this refers to the global object, whether it is strict mode or not. In this case, this === window.

The context inside a function isn’t equal to window anymore. For a function defined at the global level, the context is its parent (e.g. the component, class, service). For example, we have the component AwesomeComponent, with the function testTheContext().

testTheContext() {

    console.log(this);



    function foo() {

        console.log(this);

    }



    let arrowFoo = () => {

        console.log(this);

    }



    foo();

    arrowFoo();

}

The first console.log(this) returns “AwesomeComponent,” with all its attributes.

Things start to change at the console.log(this) from the foo(); The expected result would be “testTheContext”. But, it is “undefined.” Why?

The Context under second level function

In the above example, testTheContext() is a first level function (the parent is the class). Following this rule, foo() and arrowFoo() are second level functions. In methods, this refers to the object the method is owned by. If you declare a function inside an object’s method, its this doesn’t point to the original method’s object.

How to deal with it

The easiest method, but the ugliest, is to pass “this” as parameter to foo(), and store it (as a convention) in a variable named “that”. By doing this, we have this context in foo(). But this is not elegant at all. 

Change the context

We can dynamically change the context of any method by using call(), apply() or bind().

Call: foo.call(context, params$); 

“The Call() method calls a function with a given this value and arguments provided individually.” (6)

testTheContext(){

    console.log(this);



    function foo(){

        console.log(this);

    }



    let arrowFoo = () =>{

        console.log(this);

    }



    foo.call(this);

    arrowFoo()

}

By calling foo() with call(), console.log(this) from foo() returns “AwesomeComponent”

Apply: foo.apply(context, [param1, param2, param3]);

The apply() method works exactly like Call(), but differs in the number of arguments, supporting only 2, the context and an array of values.

Bind: var aux = foo.bind(params$)

Bind creates a new function that will have this set to the first parameter passed to bind(). A copy of the given function with the specified this value and initial arguments, if are provided, is returned.

This with Arrow Function

Since we are using ES6, we can use the most elegant method to keep this context. Unlike function expressions, where this points to the global object, in Arrow Functions this is taken from the enclosing function.  

As is evident in the captured screen from below, the syntax is very easy. 

testTheContext(){

    console.log(this);



    function foo(){

        console.log(this);

    }



    let arrowFoo = () => { //the usage of arrow function

        console.log(this);

    }



    foo.call(this);

    arrowFoo();

}

When an arrow function is used, it doesn’t create a new value for this, and this keeps on referring to the same object it’s referring to outside of the function.

Using Arrow Functions

Calling a method created with arrow function is very easy. You can see the differences between the ES5 syntax and ES6.

var multiplyES5 = function(x, y) { //ES5

    return x*y;

}



const multiplyES6 = (x, y) => {return x*y}; //ES6

It is useful to notice is that curly brackets are not needed if only an expression is present.

Also, when no parameters are used, we can simplify the code.

const phraseSplitter = phrase => phrase.split(" ");

Use cases for Arrow Functions

  1. Array manipulation
    var prices = smartPhones.map(function(smartPhone){ //ES5
    
        return smartPhone.price;
    
    });
    
    
    
    const thePrice = smartPhones.map(smartPhone => smartPhone.price); //ES6
  2. Promises and Callbacks
    aASync().then(function(){ //ES5
    
        returnbAsync();
    
    }).then(function(){
    
        returncAsync();
    
    }).done(function(){
    
       finish();
    
    });
    
    
    
    aAsync().then(() => bAsync()).then(()=> cAsync()).done(()=> finish()); //ES6
  3. This context, of course, by reducing the confusion surrounding this.


Conclusion

Arrow Functions are a very powerful and easy to use tool. It’s a good idea to start using them!

 

References

  1. https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/
  2. Image: https://caniuse.com/#feat=arrow-functions
  3. https://towardsdatascience.com/javascript-context-this-keyword-9a78a19d5786
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
  5. https://www.vojtechruzicka.com/javascript-this-keyword/
  6. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

 

Cristian Ioan Chiorescu

Front-End Developer
Cristian is a Front-End Developer at Cognizant Softvision. He’s always looking for new ways to improve his skills, learn and share knowledge with his colleagues and the community.

Latest posts by Cristian Ioan Chiorescu

Share This Article

Post A Comment

FacebookInstagramLinkedInTwitterYoutube