Javascript Arrow Function

Arrow function does not create its own execution context, but inherits this from the outer function where the arrow function is defined and these arrow functions introduced in ES6. This function

// function expression
let x = function(x, y) {
   return x * y;
}

can be written as

// using arrow functions
let x = (x, y) => x * y;

Arrow Function Syntax

The syntax of the arrow function is:

let myFunction = (arg1, arg2, ...argN) => {
    statement(s)
}

If the body has single statement or expression, you can write arrow function as:

let myFunction = (arg1, arg2, ...argN) => expression

Following things we should avoid while using arrow functions:-

  • We should not use arrow functions to create methods inside objects.
  • We cannot use an arrow function as a constructor.

Arrow Function with no arguments

If a function doesn’t take any argument, then we should use empty parentheses.

Input:-
 <script>  
	   let greet = () => document.write('Hi there');
    greet();  
</script>

Output:-


Arrow Function with single arguments

If a function has only one argument, we can omit the parentheses.

Input:-
 <script>  
	   let greet = x => document.write(x);
    greet('Hi there');
</script>

Output:-


Multiline Arrow Function

If a function body has multiple statements, we need to put them inside curly brackets {}.

Input:-
 <script>  
	   let value = (x,y) => {
          let result = x * y;
          return result;
     }
     let result1 = value(7,5);
     document.write(result1);
</script>

Output:-


Arguments binding

When we pass arguments to a regular function, we can access them using the arguments keyword. Arrow functions doesnot have this feature of arguments binding and when we try to access an argument using arrow function, it will give an error.

Input:-
 <script>  
	   let value = function () {
        console.log(arguments);
    }
    value(2,5,7);
</script>

Output:-