DEV Community

Cover image for JavaScript Arrow Functions
Yash K
Yash K

Posted on

JavaScript Arrow Functions

You might not familiar with this newer syntax of defining functions in JavaScript. It just not adds up syntactic sugar in code but it also comes with a default behavior that differs from old JavaScript functions in the context of this keyword. Don't worry, we will make it clear together!

Arrow Functions were introduced in ES6.

Let's look at the syntax of Arrow Functions first:

first-example

Output:
first-example-output

In the above example, I have defined two functions with old syntax as well with new arrow syntax. And you can see in the output, Arrow Function would not make any difference. It would work same as the old function and product output.

Also, I have demonstrated one-line syntax of arrow function and arrow function with parameters in the below example.

second-example

Now let's look at the behavior of arrow function with respect to this keyword.

Example:
this-keyword

Output:
this-keyword-output

In the above example, I have defined two constructor functions with regular function and arrow function within it. And, if you look at the output then, it might look confusing. How this output is produced? Let me clarify.

Until arrow functions, every new function defined its own this value. This proved to be less than ideal with an object-oriented style of programming. And, it can be verified by looking at the output of the p1 object. In that, this
not refers to Person1 object instead refers to window object. In this case, age would not be updated correctly.

On the other hand, An arrow function does not have its own this. Now, if you look at the person2 object which contains an arrow function within it. And, the output also proves that an arrow function does not have own this instead refers to parent2 object. thus, it would update the age correctly.

When to use an arrow function?

  • In my opinion, it shortens the syntax and code looks cleaner. But you need to be careful when you are messing with this in case of constructor function or class. It can leads to unexpected output sometimes. I personally prefer using an arrow function syntax over old syntax.

I hope you liked it and let me know your thought on this topic by commenting down below.

Follow me on twitter: https://twitter.com/ykhokhaneshiya

Top comments (0)