DEV Community

G U BHARATH CHANDRA
G U BHARATH CHANDRA

Posted on • Updated on

UNDERSTANDING ES6 ARROW FUNCTIONS

Arrow Function syntax and how to use it:

As you might know a normal function is written as below :

let square = function(num){
    return num * num;
}
Enter fullscreen mode Exit fullscreen mode

An arrow function is written as :

let square = (num) => return (num * num);
Enter fullscreen mode Exit fullscreen mode

It is as simple as it looks, we just didn't use the keyword function but instead used a fat Arrow ( => ) , it doesn't seem to be much of an improvement right now, but arrow functions are pretty useful and clean. let's see how and when to use it.

Understanding the scope of the normal and arrow functions

const result = {
name: 'place holder',

traditionalFunction: function(){
    return function(){
        console.log('name: ',this.name);
        console.log('Arguments: ' , arguments);
    }
},

fatArrowFunction: function() {
    return () => {
        console.log('name: ', this.name);
        console.log('Arguments: ' , arguments);
    }
}
};
Enter fullscreen mode Exit fullscreen mode

Here, we just have a code block for an object const result with 3 properties:

  • name,
  • traditionalFunction [which is a function],
  • fatArrowFunction [a function as well]

Let's see the difference when we create instances of the above function with arguments.


    const tradFunctionResult = result.traditionalFunction('hello','I am normal function');
    const arrowFunctionResult = result.fatArrowFunction('hello','I am Fat Arrow Function');

    tradFunctionResult();
    name:  
    Arguments:  Arguments[callee: , Symbol(Symbol.iterator): ]

    arrowFunctionResult();
    name:  place holder
    Arguments:  Arguments(2)["hello", "I am Fat Arrow Function", callee: , Symbol(Symbol.iterator): ]

Enter fullscreen mode Exit fullscreen mode

As you can see, once you create the traditionalFunction which is anonymous, the context of neither this.name nor arguments passed while creating are not available to the function.
But whereas, the the ArrowFunction has same context as of the function while creation for both this.name and arguments.
[Well, we can achieve the same effect of arrow functions in normal functions using one of or combination of bind() , call() or apply()]

note: Yes, Bind, call and apply can be ditched when using arrow functions as discussed above we have all the context we need to work with by default.But, these can still be used when the function needs to be called later in certain events when it's needed. But this case is very rare and there are some other workarounds which is out of scope for this post.

Where do arrow functions make more sense and make your life easier?

Well, let's say an array of objects need to be iterated through in which case forEach can be used with arrow function:

    this.arrayOfObjects.forEach( (element) => {
        console.log(element.name);
    });
Enter fullscreen mode Exit fullscreen mode

nice , clean and simple right!

with promises:

     this.someAsyncFunction().then( 
     result => {
         console.log('SUCCESS: ', result);
         ....
         ....
     },
     error => {
         console.log('FAILURE: ',error);
         ....
         ....
     });
Enter fullscreen mode Exit fullscreen mode

Same way with Observables:


     this.someObservable.subscribe(
        response => {
            console.log('success : ',response);
            ....
            ....
        },
        error => {
            console.log('failure : ',error);
            ....
            ....
        });
Enter fullscreen mode Exit fullscreen mode

As we know everything inside { } curly brackets is called a code block, but when we just need to invoke a single function or say do a simple computation, then we need not consider using code blocks instead, just do a oneliner as below:

this.arrayOfNumbers.map(n => n*n)
Enter fullscreen mode Exit fullscreen mode

Wrapping up

Now, we know what arrow functions are, when and how to use them and hence can write some clean and easily readable code.

Thank you for reading this post, if found are any mistakes or improvements, do let me know.

Top comments (0)