Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Can we use Hoisting with Arrow function ?

  • Difficulty Level : Basic
  • Last Updated : 16 Dec, 2021

Arrow function: Arrow function introduced in ES6, provides a concise way to write functions in JavaScript. Another significant advantage it offers is the fact that it does not bind its own. In other words, the context inside arrow functions is lexically or statically defined.

Hoising: In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

Syntax:

const geekforggeks = (argument1, argumnet2) => {
    // body
}

Like all other functions in Javascript, the arrow function is not hoisting the main reason that you cannot call them before initialization. Because hoisting is the by-default action of moving all the declarations at the top of the scope before the execution of code. JavaScript allocates memory for all its variables. So it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. The other reason is that the arrow function is anonymous.

Now lets us understand this by taking some of the examples:

Example 1: In this example,  we show that we can’t access the value before calling the function. If you call before the initialization then it will be thrown an undefined error. It means that the value is not defined inside the gfg().

Javascript




<script>
    gfg();
    console.log(input1);
    var input1 = 8;
    function gfg() {
        console.log("Hoisting in javascript")
    }
</script>

Output:

Explanation: So we can’t access the variable name input1 from above the gfg() function when we want to access it then it throws the undefined error in the console of the browser so like another programming language it can’t call before it declares. The main reason for throwing the error is JavaScript is reserved for the memory of x and place the special placeholder undefined to it 

Example 2: In this example, we will show that if we use the arrow function and then if we want to access the value then it will throw the uncaught Typeerror in the console of the browser.

Javascript




<script>
    gfg2();
    console.log(gfg2);
    var input1 = 8;
    var gfg2 = () => {
        console.log("function calling");
    }
</script>

Output: 

Explanation: Now it shows throw an uncaught type error that gfg2 is not a function. The reason is that gfg2 behaves like another variable and it allocated the memory with a placeholder like undefined.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!