JavaScript arrow functions

 JavaScript arrow functions

We already know that functions are reusable blocks of code. In JavaScript we have a way to make these shorter. We call these arrow functions.

You can check the differences of ES5, ES6 functions in the code below. The main difference to note is the omission of function and return keyword(s).

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
         // ES5

         var addES5 = function(param1param2)
            return param1 + param2;

         // ES6
         const addES6 = (param1param2=> 
                            var sum  = param1 + param2;
                           return sum;

         // ES6 single line
         const addSingleExpressionES6 = (param1param2=>  param1 + param2;

         document.write("Sum using ES5: " + addES5(10,20) + "</br>");
         document.write("Sum using ES6: " + addES6(10,20) + "</br>");
         document.write("Sum using ES6 Single Expression: " + addSingleExpressionES6(10,20) + "</br>");


Further reading/examples

Post a Comment