JavaScript Arrow Function

JavaScript Arrow Function with Examples

In this article, I am going to discuss the JavaScript Arrow function with Examples. Please read our previous article where we discussed JavaScript Immediately Invoked Function Expressions (IIFE). At the end of this article, you will understand the following pointers in detail.

  1. What are JavaScript Arrow Functions?
  2. How to convert Normal function to Arrow function in JavaScript?
  3. How Arrow function make syntax shorter from the regular function?
  4. Arrow function without parameter /zero Argument in JavaScript
  5. JavaScript Arrow function with one parameter
  6. JavaScript Arrow function with multiple parameters
  7. Arrow function with single Statement
  8. Arrow function with multiple statements
  9. JavaScript Arrow function as Anonymous function in JavaScript
  10. Arrow function with the map method
  11. Arrow function with Duplicate Named Parameter
  12. JavaScript Array Function Returning Object Literals
  13. JavaScript Arrow Function Returning Values
  14. Arrow Function Implicit and Explicit Return
  15. JavaScript Arrow Function Arguments Object binding
  16. Arrow function as a Constructor/ new Keyword
  17. JavaScript Arrow function with this keyword
  18. What is lexical Scope?
  19. Advantages Disadvantages of Arrow functions
  20. Arrow Function Limitation
JavaScript Arrow Function

Arrow function was introduced in ECMAScript 6(ES6) that provides a concise and shorthand for declaring an anonymous function.

  1. It allows us to write a function in a short and simple way in JS.
  2. Arrow functions are a concise way of writing anonymous, lexically scoped functions in ECMAScript 2015 (ES6).
  3. The Arrow functions can contain other arrow function or also regular functions.
  4. Arrow function accomplishes the same result as of regular function with fewer lines of code.
  5. The arrow function automatically binds this object to the surrounding code’s context.
  6. The value of this keyword inside the arrow function is not dependent on how they are called or how they are defined. It depends only on its enclosing context.
  7. If the arrow function is used as an inner function this refers to the parent scope in which it is defined.
How to convert Normal function to Arrow function in JavaScript

An Arrow function is very similar to a regular function in behavior, but are quite different syntactically. Steps to convert the existing ‘normal’ function into an arrow function:

  1. Remove the function keyword.
  2. Remove the opening and closing curly braces.
  3. Then Remove the parenthesis.
  4. Remove the return keyword.
  5. Remove the semicolon.
  6. Add an arrow (=>) between the argument list and the function body.
Syntax:

The syntax for an arrow function expression does not require the function keyword and uses a fat arrow => to separate the parameter(s) from the body. Below is the arrow function syntax for different cases:

x => y // Implicit return

x => {return y} // Explicit return

(x, y, z) => { return ... } // Multiple arguments

async () => { ... } // Async arrow functions

(() => { ... })() // Immediately-invoked function expression

const myFunc = x
=> x * 2 // A line break before the arrow will throw an Uncaught SyntaxError: Unexpected token '=>' error

const myFunc = x =>
x * 2 // A line break after the arrow is a valid syntax and return the output

In JavaScript, functions may be anonymously defined using the “arrow” (=>) syntax, which is sometimes referred to as a lambda expression in other languages such as python.

The simplest form of an arrow function has its parameters on the left side of => and the return value on the right side: x => x + 1 // same as function(x) {return x + 1}

The above function can be immediately invoked (IIFE) by providing an argument to the expression: (i => i + 1)(101) // -> 102

Difference of Function Syntax in ES5 and ES6

Below is the function syntax before ES6 and in ES6

Regular function – ES5 function syntax-

//Regular function
function first() {
    console.log('Hello World')
}

first();

Arrow function – ES6 Arrow function syntax

//Arrow function
first = () => {
    console.log('Hello World')
}

first();

using the arrow function, we can accomplish the same task with fewer lines of code and save time.

How Arrow function make syntax shorter from regular function

Let’s see how the arrow function help us to write shorter syntax from regular function

function getInfo() {
         //code goes here...
   console.log("Arrow function make syntax shorter from regular function");
        }

To

() => {
       //code goes here...
 console.log("Arrow function make syntax shorter from regular function");
}

But notice that we don’t have a name here. Arrow functions are anonymous. We must assign them to a variable. We can assign a regular function to a variable, like this:

let getInfo = function getInfo() {
    //code goes here...
    console.log("Arrow function make syntax shorter from regular function");
}

When we do so, we can remove the name from the function:

let getInfo= function () {
    //code goes here...
    console.log("Arrow function make syntax shorter from regular function");
}

And invoke the function using the variable name:

let getInfo= function () {
    //code goes here...
     console.log("Arrow function make syntax shorter from regular function");
}

getInfo()

That’s the same thing we do with arrow functions: Remove the word “function” and place arrow between the argument and opening body bracket { }

let getInfo= () => {
    //code goes here...
    console.log("Arrow function make syntax shorter from regular function");
}

getInfo()
JavaScript Arrow function Examples

Let’s see the Arrow function examples in JavaScript. 

Example:

<html>
<head>
    <title>JavaScript Arrow function example</title>
</head>
<body>
    <script>
        const multiply = (a, b) => a * b;
        console.log(multiply(2, 30)); // Prints: 60
    </script>
</body>
</html>

Output: 60

Arrow function Basic syntax rule for different scenario

Basic syntax rules for an arrow function are as follows:

Arguments should be passed in the small parentheses (). For only one argument, parentheses are optional. For zero argument or without arguments, there must be an empty parenthesis. If there is a single expression or statement in the function body

  1. Using parenthesis is optional
  2. Using the return statement is optional

There is a special syntax to return an object.  Either an object should be enclosed inside a small bracket ({}) or should be returned using the return statement. Let’s explore each one of the above-mentioned arrow functions basic syntax rule for different conditions in detail with example.

Arrow function without parameter /zero Argument in JavaScript

If an Arrow function takes no parameter or Arrow function with no parameters, parentheses () will be empty but they should be present.

Example:

<html>
<head>
    <title>JavaScript Arrow function without any parameter example</title>
</head>
<body>
    <script>
        //Normal function
        function intro() {
            return "Welcome to Normal function without any parameter";
        }
        console.log(intro());

        //Arrow function
        let arrowStarup = () => "Welcome to Arrow function without any parameter";
        console.log(arrowStarup());
    </script>
</body>
</html>

Output:

Arrow function without parameter /zero Argument in JavaScript

In the above example, we have removed the ‘function’ and replace it with a variable assignment, in the above example arrowStartup. The arrow functions are easier to read and have cleaner syntax.

JavaScript Arrow function with one parameter

If an Arrow function having one parameter/argument, the parentheses () around that parameter are optional and aren’t required. If we want, we can remove the parentheses.

Syntax:

One param. With simple expression, the return is not needed. param => expression

Example:

<html>
<head>
    <title>JavaScript Arrow function with one parameter example</title>
</head>
<body>
    <script>
        //Normal function
        function isNegative(number) {
            return number <= 0
        }
        console.log("Normal function: ", isNegative(3));

        //Arrow function having one parameter without parentheses
        let arrowIsNegative = number => number <= 0;

        //Arrow function having one parameter with parentheses
        let arrowIsNegativeWithParn = (num) => num <= 0;

        console.log("Arrow function :", arrowIsNegative(-1));
        console.log("Arrow function with Parentheses :", arrowIsNegativeWithParn(5));
    </script>
</body>
</html>

Output:

JavaScript Arrow function with one parameter

In the above example snippet, since there is 1 parameter so we can remove the parentheses around the parameter number. Again, the functions are exactly the same.

JavaScript Arrow function with multiple parameters

If the Arrow function has multiple arguments or no argument, we must put parentheses () around the arguments.

Syntax:

Multiple params require parentheses. With simple expression return keyword is not needed: (param1, param2, paramN) => expression

Example: JavaScript Arrow function with multiple parameters Examples

<html>
<head>
    <title>JavaScript Arrow function with Multiple and No parameters example</title>
</head>
<body>
    <script>
        //Normal function
        function total(a, b) {
            return a + b;
        }
        console.log("Normal function multiple param: ", total(5, 7));

        //Arrow function having multiple parameters
        let arrowTotal = (a, b) => a + b;
        console.log("Arrow function multiple param :", arrowTotal(11, 14));

        //Normal Function (no arguments)
        let a = 4; let b = 2;
        function sum() {
            return a + b + 100;
        }
        console.log("Normal function with no param:", sum());

        //Arrow Function (no arguments)
        let x = 4; let y = 2;
        let arrowSum = () => x + y + 100;
        console.log("Arrow function with no param:", arrowSum());
    </script>
</body>
</html>

Output:

JavaScript Arrow function with multiple parameters

Everything after the arrow => is assumed to be returned. a+b with multiple parameters will be returned because there aren’t any brackets { } or return statements and the same happen for x+y with no parameter also. The above fours are exactly the same functions, just the second and fourth one is using arrow function syntax.

Arrow function with single Statement

Let’s see the example of Arrow function body having a single statement

//Without Arrow Function
hello = function () {
           return "JavaScript Tutorial";
} 

//With Arrow Function
hello = () => {
    return "JavaScript Tutorial";
}

It gets shorter!

If the Arrow function body has only one statement, and the statement returns a value, we can remove the brackets { } and the return keyword and write all on a single line hello = () => “JavaScript Tutorial”;

Parameters are passed in the parentheses:

If we have parameters, we pass them inside the parentheses. In fact, if we have only one parameter, we can skip the parentheses () as well

Arrow Function with multiple parameters hello = (param1, param2) => console.log(“JavaScript” + param1 + param2);

Arrow Function with one parameter hello = (param1) => console.log(“JavaScript” + param1);

Arrow Function without Parentheses hello = param1 => console.log(“JavaScript Tutorial” + param1);

Example:
<html>
<head>
    <title>JavaScript Arrow function with single statement example</title>
</head>
<body>
    <script>
        //Normal function
        function sum(x, y) {
            return x + y
        }

        setTimeout(function () {
            console.log("Normal function executed after 1sec");
        }, 1000);

        console.log('Normal function:', sum(10, 20));

        //Arrow function
        let arrowSum = (x, y) => x + y;//doesn’t need return keyword for single statement

        setTimeout(() => console.log("Arrow function executed after 1sec"), 1000);
        console.log('Arrow function:', arrowSum(20, 30));
    </script>
</body>
</html>

Output:

JavaScript Arrow function with single statement example

JavaScript Arrow function with multiple statements

If the Arrow function body needs multiple lines of statements or expression, we must enclose them in curly braces { } also use a return keyword within them to return a value. If we use curly braces, then we need an explicit “return” keyword else it will not return a value rather show undefined

Syntax:

Multiple params require parentheses. Multiline statements require body brackets and return:

(param1, paramN) => {
            let a = 1;
            return a + param1 + paramN;
}

Example: JavaScript Arrow function with Multiple statements/expression example

<html>
<head>
    <title>JavaScript Arrow function with Multiple statements/expression example</title>
</head>
<body>
    <script>
        //Normal function
        function multiStatmnt(a, b) {
            let chunk = 100;
            return a + b + chunk;
        }
        console.log("Normal function multiple statements: ", multiStatmnt(5, 7));

        //Arrow function having multiple statements/expression
        let arrowMultiStatmnt = (a, b) => {
            let chunk = 100;
            return a + b + chunk;
        };
        console.log("Arrow function multiple statements :", arrowMultiStatmnt(11, 14));

        //Arrow function having multiple statements without return keyword
        let arrowMultiStatmntNoRetrn = (a, b) => {
            let chunk = 100;
            a + b + chunk;
        };
        console.log("Arrow function multiple statements without Return keyword:", arrowMultiStatmntNoRetrn(11, 14));

    </script>
</body>
</html>

Output:

JavaScript Arrow function with Multiple statements/expression example

Arrow functions are a one-liner function. They come in with two suggestion

Without curly braces: (…args) => function expression – the right-hand side is an expression. The function executes it and returns the desired result

With curly braces: (…args) => {function body } – the brackets allow us to write multiple statements inside the function but that needs an explicit return keyword to return something.

Arrow function as Anonymous function in JavaScript

An Arrow function can be used with the Anonymous function to attached addEventListener to button control.

Example: JavaScript Arrow function with Anonymous function example

<html>
<head>
    <title>JavaScript Arrow function with Anonymous function example</title>
</head>
<body>
    <button id="myNormalBtn">Normal Function-Click Me</button>
    <button id="myArrowBtn">Arrow Function-Click Me</button>

    <script>
        //Normal function
        document.getElementById("myNormalBtn").addEventListener('click', function () {
            console.log('Normal function was clicked');
        })

        //Arrow function with Anonymous function
        document.getElementById('myArrowBtn').addEventListener('click', () => {
            console.log('Arrow function was clicked');
        })
    </script>
</body>
</html>

Output:

JavaScript Arrow function with Anonymous function example

In the above code, the Arrow function attached as an Anonymous function is fired when we clicked on the button which is the same as when clicking on the Normal function button.

Arrow function with the map method

Example:

<html>
<head>
    <title>JavaScript Arrow function with map() method example</title>
</head>
<body>
    <script>
        //Normal function
        let arr = [1, 2, 3]
        let squares = arr.map(function (x) {
            return x * x;
        });
        console.log('Normal function map(): ', squares);

        //Arrow function with map() method
        var array = [1, 2, 3]
        var arrowSquares = array.map(x => x * x);
        console.log('Arrow function map(): ', arrowSquares)
    </script>
</body>
</html>

Output:

Arrow function with Duplicate Named Parameter

While passing the Duplicate Named Parameter to the method is allowed in Regular function. When in “use strict” mode, this will throw Error: Syntax Error: Duplicate parameter name not allowed in this context.

Whereas passing the Duplicate Named Parameter to the method is not allowed in the Arrow function. It will throw Error regardless of strict or non-strict mode.

Example: Normal function with Duplicate Named Parameter
<html>
<head>
    <title>JavaScript Normal function with Duplicate Named Parameter example</title>
</head>
<body>
    <script>
        //Normal function
        function multiply(a, a) {
            return a * a;
        }
        console.log("Normal function Duplicate Named Parameter : ", multiply(5, 7));        
    </script>
</body>
</html>

Output: Normal function Duplicate Named Parameter : 49

Example: Arrow function with Duplicate Named Parameter
<html>
<head>
    <title>JavaScript Arrow function with Duplicate Named Parameter example</title>
</head>
<body>
    <script>        
        //Arrow function having Duplicate Named Parameter
        let arrowMultiply = (a, a) => a * a;
        console.log("Arrow function Duplicate Named Parameter :", arrowMultiply(11, 14));
    </script>
</body>
</html>

Output:

JavaScript Arrow function with Duplicate Named Parameter example

JavaScript Array Function Returning Object Literals

We need to keep in mind that while returning object literals with Arrow Function using the concise body syntax i.e.: params => { object: literal } will not work as expected. To understand this, see below example

<html>
<head>
    <title>JavaScript Arrow function Returning Object literals example1</title>
</head>
<body>
    <script>
        var arrowFunc = () => { price: 10 };
        // Calling func() returns undefined!
        console.log("Arrow function(arrowFunc) Returning Object literal :", arrowFunc());

        var arrowFunc1 = () => { price: function() { } };
        // SyntaxError: function statement requires a name
        console.log("Arrow function(arrowFunc1) Returning Object literal :", arrowFunc1());

    </script>
</body>
</html>

Output:

JavaScript Array Function Returning Object Literals

This is because the code placed inside the curly bracket ({}) is parsed as a sequence of an element that is treated as a label, not as a key in an object literal. We must wrap the object literal in parentheses like- ({ object: literal })

Example: JavaScript Arrow function Returning Object literals example
<html>
<head>
    <title>JavaScript Arrow function Returning Object literals example2</title>
</head>
<body>
    <script>
        //Normal function
        var objectReturn = function objectReturn(x) {
            return { price: 100 + x };
        }
        console.log("Normal function Returning Object literal : ", objectReturn(5));

        //Arrow function Returning Object literals
        let arrowObjectReturn = x => ({ price: 100 + x })
        console.log("Arrow function Returning Object literal :", arrowObjectReturn(5));

    </script>
</body>
</html>

Output:

JavaScript Arrow function Returning Object literals

JavaScript Arrow Function Returning

While returning the function from arrow functions it displays undefined in place of function. This is due to the empty arrow function as Empty arrow function returns undefined. But why this is returning will see. First, go through the example first.

Example:

<html>
<head>
    <title>JavaScript empty Arrow function and Returning value example</title>
</head>
<body>
    <script>
        //Arrow function returning value
        let arrowRetnVal = () => 10;
        console.log("Arrow function Returning value : ", arrowRetnVal());

  //An empty arrow function returns undefined
        let arrowRetnFunc = () => { };
        console.log("Arrow function Returning function : ", arrowRetnFunc());
    </script>
</body>
</html>

Output:

JavaScript empty Arrow function and Returning value example

We might expect {} instead of undefined. This is because the curly braces are part of the syntax of the arrow functions, so arrowRetnFunc will return undefined. It is possible to return the {} object directly from an arrow function, by enclosing the return value with brackets.

Example:
<html>
<head>
    <title>JavaScript Arrow function, Function Returning empty object two ways example</title>
</head>
<body>
    <script>
        //Arrow function 
        let arrowRetnFunc1 = () => ({});
        console.log("Arrow function Returning function-1 : ", arrowRetnFunc1());

        let arrowRetnFunc2 = () => { return {} };
        console.log("Arrow function Returning function-2 : ", arrowRetnFunc2());
    </script>
</body>
</html>

Output:

JavaScript Arrow function, Function Returning empty object two ways example

If we need to return an empty object from an arrow function, we can return in one of two ways mentioned in the code snippet.

JavaScript Arrow Function Implicit Return

Arrow functions can implicitly return values by simply omitting the curly braces that traditionally wrap a function’s body if their body only contains a single expression. That means in Implicit return keyword is not need with one or multiple params with a single expression or body statement.

Example: Arrow function Implicit Return
<html>
<head>
    <title>JavaScript Arrow function Implicit Return example</title>
</head>
<body>
    <script>
        //Arrow function simple Implicit Return
        let arrowImplicitReturn = x => x * x + 10;
        console.log("Arrow function Implicit Return : ", arrowImplicitReturn(5));
    </script>
</body>
</html>

Output: Arrow function Implicit Return : 35

When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not mistaken for the opening of the function’s body.

Example: Arrow function Implicit Return with Object literals
<html>
<head>
    <title>JavaScript Arrow function Implicit Return with Object literals example</title>
</head>
<body>
    <script>
        //Arrow function Implicit Return with object literals without parentheses
        let arrowImplctRetrn_objLitrls_1 = () => { price: 10 } //returns undefined
        console.log("Arrow function Implicit Return without parentheses : ", arrowImplctRetrn_objLitrls_1());

        //Arrow function Implicit Return with object literals with parentheses
        let arrowImplctRetrn_objLitrls_2 = () => ({ price: 10 })
        console.log("Arrow function Implicit Return with parentheses : ", arrowImplctRetrn_objLitrls_2());

    </script>
</body>
</html>

Output:

JavaScript Arrow function Implicit Return with Object literals example

Array Function Explicit Return in JavaScript

Arrow functions can behave very similar to classic Regular/Named functions in that you may explicitly return a value from them using the return keyword; simply wrap your function’s body in curly braces, and return a value:

Example:

<html>
<head>
    <title>JavaScript Arrow function Explicit Return example</title>
</head>
<body>
    <script>
        //Arrow function Explicit Return
        let arrowExplicitReturn = x => {
            return x * x + 10;
        }
        console.log("Arrow function Explicit Return : ", arrowExplicitReturn(5));

    </script>
</body>
</html>

Output: Arrow function Explicit Return :35

Arguments Object binding

Regular functions have arguments binding. Arrow functions do not have arguments binding. An arrow function is a lightweight version of Regular functions with a focus on being short and lexical this. Simultaneously, arrow functions do not provide a binding for their own arguments object.

As a valid alternative use the rest parameters to achieve the same result. Arrow functions do not have their own arguments object; therefore, arguments would simply refer to a variable pass in the current scope. Because of this, arrow functions are also not aware of their caller/callee.

As the lack of an arguments object can be a limitation in some edge cases, rest parameters are generally a suitable alternative.

Example: Arrow function Arguments binding
<html>
<head>
    <title>JavaScript Arrow function Arguments binding example</title>
</head>
<body>
    <script>
        //Normal function
        let argsBinding = function () {
            return arguments;
        }
        console.log("Normal function arguments binding : ", argsBinding("5", 6, 7));

        //Arrow function arguments Binding 
        let arrowArgsBinding = () => arguments
        console.log("Arrow function arguments binding: ", arrowArgsBinding("5", 6, 7));

    </script>
</body>
</html>

Output:

JavaScript Arrow function Arguments binding example

In most of the cases, using rest parameters is the best alternative to using an arguments object binding.

Example: Arrow function Arguments binding with rest parameters
<html>
<head>
    <title>JavaScript Arrow function Arguments binding using rest Parameters example</title>
</head>
<body>
    <script>
        //Arrow function arguments Binding using rest parameters
        let arrowArgsBidng_RestPram = (...args) => args
        console.log("Arrow function arguments Binding using rest parameters : ", arrowArgsBidng_RestPram("5", 6, 7));

    </script>
</body>
</html>

Output:

JavaScript Arrow function Arguments binding using rest Parameters example

Arrow function as a Constructor/ new Keyword

Regular functions can be used as constructor functions while Arrow functions cannot be used as constructor functions.

Why?

Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using a new keyword. Since arrow functions are not constructible, they can never be called using the new keyword.

Arrow functions cannot be used as constructors as it will throw a TypeError when used with a new keyword.

Example: Arrow function with new keyword without parameter/ parameter less constructor
<html>
<head>
    <title>JavaScript Arrow function with new keyword without parameter example</title>
</head>
<body>
    <script>
        //Normal function
        const normalFunc = function () {
            return "normalFunc constructor";
        }
        const a = new normalFunc();
        console.log("Normal function with new keyword: ", a);

        //Arrow function with new keyword without parameter
        const arrowfunc = () => {
            return "arrowfunc constructor";
        }
        const b = new arrowfunc(); // -> Uncaught TypeError: arrowfunc is not a constructor...
        console.log("Arrow function with new keyword: ", b);

    </script>
</body>
</html>

Output:

JavaScript Arrow function with new keyword without parameter example

Example: Arrow function with new keyword and parameter / parameterize constructor
<html>
<head>
    <title>JavaScript Arrow function with new keyword and parameter example</title>
</head>
<body>
    <script>
        //Normal function
        function User(name, age, sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        const Shagufta = new User("Shagufta", 23, "Female");
        console.log("Normal function using new keyword with parameters: ", Shagufta);

        //Arrow function with new keyword and parameter
        const Person = (name, age, sex) => {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        const John = new Person("John", 23, "Male"); // -> Uncaught TypeError: John is not a constructor...
        console.log("Arrow function using new keyword with parameters: ", John);

    </script>
</body>
</html>

Output:

JavaScript Arrow function with new keyword and parameter example

From the above code, we can say that Arrow functions are callable but not constructible. Regular functions are callable and constructible.

JavaScript Arrow function with this keyword

What makes arrow function really impressive is the fact that they redefine ‘this’ keyword inside of them as opposed to normal function

With regular function, the value of ‘this’ is set based on how the function is called. With the arrow function, the value of ‘this’ is based on the function’s surrounding context. This means that the value of ‘this’ inside an arrow function is the same as the value of this outside the function.

Unlike a regular function, an arrow function does not bind this object. Instead, this is bound lexically i.e.: this keeps its meaning from its original context.

What do we mean by that?

The value of this keyword inside the arrow function is not dependent on how they are called or how they are defined. It depends only on its enclosing context. As we know that arrow functions are lexically scope.

What is lexical Scope?

Lexical Scope also called static scope. Every inner level can have access to its outer level.

Let us understand this with some examples:

<html>
<head>
    <title>JavaScript Arrow function Lexical Scope example</title>
</head>
<body>
    <script>
        var scope = "I am global";
        function whatIsFuncScope() {
            var scope = "I am just a local";
            function func() { return scope; }
            return func;
        }

        console.log("whatIsFuncScope-lexical Scope : ", whatIsFuncScope()());
    </script>
</body>
</html>

Output: whatIsFuncScope-lexical Scope : I am just a local

The above code will return “I am just a local”. It will not return “I am a global”. Because the function func() counts where it was originally defined which is under the scope of function whatIsFuncScope.

It will not worry from whatever it is being called (the global scope/from within another function even), that’s why global scope value “I am global” will not be printed.

This is called lexical scoping where “functions are executed using the scope chain that was in effect when they were defined” – according to JavaScript Definition Guide. Lexical scope is a very powerful concept.

In the arrow function, this keyword refers to the object which made up the function. But in Normal function, this keyword refers to the element which calls the function via event. Since all global variables and functions are inside the window. this keyword inside the global function will refer to the window object.

ES6 arrow function cannot be bound to this keyword, so it will lexically go up in function scope, and use the value of this object in the scope in which it was defined.

The Regular function has its own binding.

The source of this is an important distinguishing aspect of arrow functions:

  • Regular functions have a dynamic this; its value is decided by how they are called
  • Arrow functions have a lexical this; its value is decided by the surrounding scope.

The following variables are all lexical inside arrow functions:

  • arguments
  • super
  • this
  • new.target

With a regular function, this represents the object that calls the function.

Example:
<html>
<head>
    <title>JavaScript Regular function this keyword example</title>
</head>
<body>
    <p id="demo"></p>
    <button id="btn">Click Me</button>

    <script>
        //Normal function
        hello = function () {
            document.getElementById("demo").innerHTML += this;
        }

        //The Window object calls the function
        window.addEventListener("load", hello);

        //A button object calls the function
        document.getElementById("btn").addEventListener("click", hello);
    </script>
</body>
</html>

Output:

JavaScript Regular function this keyword example

With an arrow function, this represents the owner of the function

Example:
<html>
<head>
    <title>JavaScript Arrow function this keyword example1</title>
</head>
<body>
    <p id="demo"></p>
    <button id="btn">Click Me</button>

    <script>
        //Arrow function
        hello = () => {
            document.getElementById("demo").innerHTML += this;
        }

        //The Window object calls the function
        window.addEventListener("load", hello);

        //A button object calls the function
        document.getElementById("btn").addEventListener("click", hello);
    </script>
</body>
</html>

Output:

JavaScript Arrow function this keyword example

Regular function refers this to the window scope. Whereas arrow function, do not refers this to the window, rather they execute in the scope they are created. Below is the example which elaborates it correctly.

Example:
<html>
<head>
    <title>JavaScript Arrow function this keyword example2</title>
</head>
<body>
    <script>
        window.count = 1;
        //Normal function
        function counter() {
            this.count = 10;
            setTimeout(function () {
                console.log("Normal function counter : ", this.count)
            }, 1000);
        }
        var counter = new counter();

        //Arrow function
        function arrowCounter() {
            this.count = 10;
            setTimeout(() => {
                console.log("Arrow function counter : ", this.count)
            }, 1000);
        }
        var arrowCounter = new arrowCounter();
    </script>
</body>
</html>

Output:

Advantages of Arrow functions

Two benefits of arrow functions:

  1. Shorter Syntax-the arrow function provides a convenient and short syntax to write a function expression.
  2. No binding of this
Disadvantages of Arrow function:
  1. Since Arrow functions are declared with the var keyword, they do have the characteristic of a variable. So, calling an arrow function before declaration will throw an error. That means the arrow function cannot be hoisted.
JavaScript Arrow function cannot be hoisted

Example:

<html>
<head>
    <title>JavaScript Arrow function cannot be hoisted example</title>
</head>
<body>
    <script>
        normalFunc();
        arrowFunc();

        //Normal function
        function normalFunc() {
            console.log("This Normal fnction can be called event before declaration");
        }
        //Arrow function cannot be hoisted
        let arrowFunc = () => {
            console.log("This Arrow function can be called only after declaration");
        }
    </script>
</body>
</html>

Output:

Arrow Function Limitation

So far, we have seen arrow function with the different condition on that we can conclude that though arrow function is the alternative to the regular function, its limited and cannot be used in all situations such as

  • An arrow function doesn’t have an arguments object
  • The arrow function cannot be used as constructors or cannot be called using a new keyword
  • An arrow function does not have its own binding to this keyword, mean use the value of this in the scope in which it was defined.

In the next article, I am going to discuss JavaScript Set Data Structure with Example. Here, in this article, I try to explain the JavaScript Arrow function with examples. I hope this JavaScript Arrow function article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Arrow function article.

Leave a Reply

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