DEV Community

kheersagar parja
kheersagar parja

Posted on • Edited on

Regular Function VS Fat Arrow Function

Regular function

function ATraditionalFunc () {
  console.log("inside traditonal function")
}
ATraditionalFunc()
Enter fullscreen mode Exit fullscreen mode

Output

inside traditonal function
Enter fullscreen mode Exit fullscreen mode

Arrow Function or Fat Arrow function

const AFatArrowFunc = () =>{
  console.log("inside fatArrowFunc function")
}
AFatArrowFunc()
Enter fullscreen mode Exit fullscreen mode

Output

inside fatArrowFunc function
Enter fullscreen mode Exit fullscreen mode

Both behaved the same then what is the difference??

If we call both functions before its initialization what will happen?

ATraditionalFunc()
AFatArrowFunc()
function ATraditionalFunc () {
  console.log("inside traditonal function")
}
const AFatArrowFunc = () =>{
  console.log("inside fatArrowFunc function")
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

We got a Reference Error, why did it happened?
There are two reasons :

Hoisting

JavaScript 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.
for more information: [click here]

test
When Execution is in Line no. 1
Regular function in allocated memory in Global scope whereas Fat Arrow function in allocation in Script scope. Therefore when we try to access a function before its Initialization it gives us reference error.

If hoisting is the only reason then, what happens if we do this ?

ATraditionalFunc()
AvarfatArrowFunc() 
function ATraditionalFunc () {
  console.log("inside traditonal function")
}

var AvarfatArrowFunc = () =>{
  console.log("inside varfatArrowFunc function")
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

we changed const to var and output is still the same.
Here comes how JavaScript treats variables and functions.

Value initialization

Image description

when JavaScript allocates memory it assign undefined to Fat Arrow function because JS treats it as a variable and whole function to Regular function, refer above image.

Top comments (0)