0

fun() // **Arrow Function (fun) is called before function definition**

var fun = () => {

  console.log("xdssdyz");
}

// How it predicts that fun is not a function , according to execution context and function hoisting .

Ankit
  • 9
  • 3
  • 1
    Doesn't matter that it's an arrow function; this is a prime example of why functions should be declared using the `function` keyword (unless they have to be arrow functions) –  Aug 22 '22 at 15:18
  • Does this answer your question? [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Ivar Aug 22 '22 at 15:19
  • There is no hoisting for variables. – Jared Farrish Aug 22 '22 at 15:19
  • "How it predicts that fun is not a function ," - quite the opposite, it is saying it doesn't know what `fun` is and thus invoking it with `fun()` is not defined. Move the `fun()` call to underneath the definition and it should work. The runtime parser isn't doing anything magical, this is just a standard case of declare before use. – h0r53 Aug 22 '22 at 15:22
  • @JaredFarrish _"Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, **variables** or classes to the top of their scope, prior to execution of the code. ... Variable and class declarations are also hoisted, so they too can be referenced before they are declared. Note that doing so can lead to unexpected errors, and is not generally recommended. "_ https://developer.mozilla.org/en-US/docs/Glossary/Hoisting – jabaa Aug 22 '22 at 15:35
  • @jabaa Clarification: The variable is hoisted as declared but isn't set. It wouldn't make sense to hoist the entire expression. – Jared Farrish Aug 22 '22 at 15:42

3 Answers3

2

You're trying to call

fun()

before the declaration of it.

0

With hoisting var, the fun variable will be undefined before the declaration, and you try to execute undefined as a function, that's why it gives an error `Uncaught TypeError: fun is not a function

Mina
  • 14,386
  • 3
  • 13
  • 26
0

arrow function isn't hoisted in javascript. An arrow function is not actually a function: it is an expression of a function and expressions is not hoisted in javascript. Basically an anonymous function is kept in a variable of arrow function instead of declaring it. That's why such thing happens. If you want your function to be hoisted, declare it with function keyword, that's how js understands it as a function

Riddik
  • 2,565
  • 1
  • 11
  • 21
Juel Hossain
  • 11
  • 1
  • 3