When To Avoid Use of An Arrow Function in JavaScript?

When To Avoid Use of An Arrow
Function in JavaScript?

Every year or every day there are so many changes you find in programming languages. you are getting newer & newer versions of the programming language you are using currently. The same thing is happening with JavaScript as well. In the version ES6, the JavaScript language becomes more usable with arrow functions, classes & a lot more.

One of the most useful factors included in ES6 JavaScript is the Arrow function. Though it is so useful, it still confuses people while using it.

Now, let's see when not use the arrow function in JavaScript:

1. While defining methods on an object

In JavaScript method is nothing but a function stored in the property of the object. When we call a method, this becomes an object to which methods belong. A. Object Literals - As the arrow function has a short syntax we can use it for method definition.

Now, let's see an example, how to use the arrow function for method definition

const add = {

     arr1 : [4,6,3];

     sum : () => {

         console.log (this === window);

         return this.array.reduce((result,item)=> result +

item);

}

};

console.log(this === window);

add.sum();

In the above program sum() method is defined with the arrow function. But after invoking this method, it throws a TypeError, because this.array is evaluated to undefined.

When we invoke a method sum() on add object, the context remains as windows. It happens because the arrow function binds the context lexically with the window object.

And executing this.array is window.array which is not defined anywhere in the code.

To make the above code work properly you can use the shorthand syntax as follows:

const add = {

arr1 : [4,6,3];

sum : () => {

console.log (this === add);

return this.array.reduce((result,item)=> result + item);

}

};

add.sum();

This code results in the correct sum as 13 after invoking a function sum(). This is because the sum is a regular function & this invocation of add.sum() is the add object & this.array is the array reference, therefore the sum of array elements gets calculated correctly.

B. Object Prototype

The same rule is applicable when we define methods on a prototype object also. So instead of using the arrow function, we can use function expression for the same. Let's see an example

function myPet(name)

{

this.petname = name;

}

this.prototype.sayPetName = () => {

console.log(this === window);

return this.petname;

};

const pet = new myPet('Rocky');

pet.sayPetName();

The above code will give a result as undefined due to the above-discussed reason.

Let's solve this problem with Regular Expression. function myPet(name)

{

this.petname = name;

}

myPet.prototype.sayPetName = function() {

console.log(this === pet);

return this.petname;

};

const pet = new myPet('Rocky');

pet.sayPetName();

The above code will print a result as Rockey. Here, sayPetName is a regular function is changing the context into pet object when called as a method: pet.sayPetName();

2. On callback functions with dynamic context

We all know that this is a powerful object in JavaScript. It can change the context depending upon how the function is called. often context is the target object on which invocation happens.

The arrow function binds the object statically on the declaration & it's not possible to bind it dynamically. We often use event listeners to DOM elements in client-side programming. An event always triggers the handler function with this as a target element.

The following example shows the use of an arrow function as an event handler

const btn = documet.getElementById('btn1');

btn.addEventListener('click', () => {

console.log(this === window);

this.innerHTML = 'You just clicked on this button';

});

Here, in this example, this is a window in an arrow function defined in the global context. when a click event happens. the browser tries to invoke the handler function with btn context. As the arrow function doesn't change its predefined context, this.innerHTML is equivalent to the window.innerHTML with no sense.

You can use the function expression, which changes this depending upon the target element.

Let's see an above code with function expression

const btn = documet.getElementById('btn1');

btn.addEventListener('click', function() => {

console.log(this === btn);

this.innerHTML = 'You just clicked on this button';

});

Here, in the above code, when the user clicks the button, this is now an event handler function in the btn. Therefore, this.innerHTML modifies the button text correctly to reflect the clicked status.

3. While invoking constructors

this is a constructor invocation of the newly created object. While executing a new Myfunction(), the context of the MyFunction() becomes a new object & this instanceOf MyFunction === true.

Just remember that you can't use the arrow function as a constructor in JavaScript. When you use it, JavaScript throws an exception for doing this. Because the arrow function constructor doesn't make any sense & causes ambiguity.

Let's see what will happen when we use the arrow function as a constructor.

const msg = (txt) => {

this.txt = txt ;

}

const welcomeMsg = new msg ("Welcome to JavaScript");

while executing a new msg ("Welcome to JavaScript"), where msg is an arrow function, JavaScript throws a TypeError that msg can not be used as a constructor.

This example can be fixed using the function expression. Let's see it - const msg = function (txt) {

this.txt = txt ;

}

const welcomeMsg = new msg ("Welcome to JavaScript"); console.log(welcomeMsg.txt);

An arrow function has a property to omit the argument parenthesis (), blocking of curly braces {} & return if the function body has only one statement. This helps in writing very short functions.

Let's see an example for this

const mul = (a,b) => b === undefined ? a*b : b*a;

const double = mul(2);

double(3);

mul(2,3);

The above code results in 6. The above code is short but it's difficult to understand. Still, it is so much more useful than writing the 10 lines of code.

Conclusion

Without a doubt, the arrow function is a great addition to the ES6 version of JavaScript. When we used it correctly, it brings simplicity in code where we have to use a bind() method. It also makes a code lighter

You've successfully subscribed to HTML5Awesome
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.