Consider the following snippet:
function myFunction(a){
console.log(a);
}
myFunction(1);
//1
var oldFunction = myFunction;
function myFunction(b){
console.log('intercept');
oldFunction(b);
}
myFunction(1);
//too many calls, console outputs intercept indefinitely
The code doesn't work properly and outputs "intercept" indefinitely. Then I searched Stack Overflow and I found out that the following modified code worked as expected:
function myFunction(a){
console.log(a);
}
myFunction(1);//1
var oldFunction = myFunction;
var myFunction = function(b){
console.log('intercept');
oldFunction(b);
}
myFunction(1);
//intercept
//1
My question is: why doesn't first code work as expected? I know there are differences between function declarations and function expressions (primarily due the hoisting behavior), but I'm still confused.
EDIT: Indeed is a hoisting behavior misunderstood. I realize that the first code works if I execute it as the following:
eval(`function myFunction(a){
console.log(a);
}
myFunction(1);
//1
var oldFunction = myFunction;`);
eval(`function myFunction(b){
console.log('intercept');
oldFunction(b);
}
myFunction(1);`);
//1
//intercept
//1
This closes the question. When I execute the code separately becomes clear that the function myFunction was being hoisting.