JavaScript

Arrow Functions in JavaScript

Basically, Arrow Functions in JavaScript provide us a way to simplify coding the user-defined functions. Further, they let us define anonymous functions.

Since, arrow functions provide us a way to write shorter syntax, by including arrow functions in script single statement functions can be created fast and prevent unnecessaey coding.

However, there are certain differences with the use of arrow functions. Also, the arrow functions offer several benefits over traditional functions.

Benefits of Arrow Functions

  1. Shorter and simpler syntax
  2. No need of specifying the function name
  3. Implicitly returning value
  4. Automatic binding of this to the context of surrounding code

How to Write Arrow Functions in JavaScript

The following code shows an arrow function that returns a constant value.

x=()=>5;

In order to call this function, just use the expression x() and enclose it in the <script> tag as shown below.

<script>
x=()=>5;
document.write(x());
</script>

Even, you can pass parameters to an arrows function. For example, consider the following code.

<script>
x=(a)=>a+1;
document.write(x(14));
</script>

As shown above, we pass a parameter named a and the function increments it by 1 and returns the value. Also, it is possible for an arrow function to have multiple statements. However, in that case, an explicit return statement is required. The following code shows an example of an arrow function containing multiple statements.

<script>
x=()=>{
a=10;
b=20;
return a+b;
}
document.write(x());
</script>

Examples of Arrow Functions in JavaScript

The following section provides some examples of using arrow functions in JavaScript.

At first, a simple function of computing factorial of a number is given below.

 var x=(n)=>{
       let f=1;
       for(let i=1;i<=n;i++)
       {
		f=f*i;
       }
       return f;
    }

You can find the complete program here.

The following example shows how to display table of a number using an arrow function.

var x=(n)=>{
       let t=1;
       let str='';
       for(let i=1;i<=10;i++)
       {
		t=n*i;
                str=str+n+'X'+i+'='+t+'<br/>';
       }
       return str;
    }

Also, the complete program is available here.

Another example of implementing a power function is shown below.

var x=(a,b)=>Math.pow(a, b);

In order to view the complete code click here. As an illustration of using the arrow function to find factorial of n numbers, look at the following code.

var x=(n)=>{
      let f=1;
      let str='';     
      for(let i=1;i<=n;i++)
      {
        for(let j=1;j<=i;j++)
        {
	    f=f*j;
            
        }
        str+='Factorial of '+i+' = '+f+'<br/>';
	f=1;
      }
      return str;
    }

In order to find the complete example click here.


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *