Regular function
function ATraditionalFunc () {
console.log("inside traditonal function")
}
ATraditionalFunc()
Output
inside traditonal function
Arrow Function or Fat Arrow function
const AFatArrowFunc = () =>{
console.log("inside fatArrowFunc function")
}
AFatArrowFunc()
Output
inside fatArrowFunc function
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")
}
Output
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]
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")
}
Output
we changed const to var and output is still the same.
Here comes how JavaScript treats variables and functions.
Value initialization
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)