Learning JavaScript-- Understanding the ES6 Arrow Functions and comparing it with normal functions

in #programming4 years ago

Hello People!
In the last posts, we have discussed the JavaScript Functions. In this tutorial, we are going through the most useful and advanced feature that comes with the ES6 version of JavaScript. So without wasting time let's start the tutorial.

image.png
Image Source

  • In the below snap you can see that we have created a function (a simple function) that takes two parameters. Assign that to a variable named add and then printing the value on the console.
    image.png

  • To understand the ES6 Arrow function javascript let's convert the simple function to an arrow function.

  • To convert the simple function to an arrow function, first of all, remove the keyword function and assign the function to a variable. And the reason we have to do this assignment here is that normal functions already create a variable of the name sum but as we don't have the function keyword so we now need to create our own variable to store this function.

image.png

  • In the above snap you can see that we have removed the function keyword and assign the function to a variable named sum1 and after that, we need an arrow sign which is the combination of = equal and > greater sign.

  • If we have only 1 line of code we can make it simpler and easier by removing the brackets as well.

image.png

  • even we don't need the return statement because anything after the brackets is assumed as a return.

  • Assume we have a function with the nameisPositive that takes one parameter.

image.png

  • To convert this function into an arrow function, first of all, we will remove the function keyword and then assign it to a variable. I am going to write the exact function below the normal function.

image.png

  • Now to make it more simple we can remove the brackets and the return statement.

image.png

  • Now we have a function that returns a random number without any parameters.

image.png

  • To convert this to an arrow function we will do the same procedure.

image.png

  • And to make it simpler we can remove the brackets and return statements.

image.png

  • We can see the difference between these functions. But this is not what makes the arrow functions great. This is just a very basic feature of arrow function there are more features that we will discuss in the upcoming post but for now, being beginners I think this much is enough for this level.

So take care and see you with a new post.