I spend lot of time to find out the reason of incorrect function behavior and was really surprized of my investigation result.
I will compress all my complicated logic and will represent using very simple example:
I have some executor:
function run() {
//define one more fn inside
function render() {
//returns execution result
return 1;
}
//I use this execution result
console.log(render()); //expect 1, but was 2
//here I have lot of code added by other developers
//and after some refactoring and code merge was added
//one more implementtaion
//it was done by accidentally as merge issue
function render() {
return 2;
}
}
My big surprise that console.log
prints 2
. Only after detecting second function with the same name I can try to explane this using popular words like hoisting, but I dont understand how this possible in this concrete example.
Also, when second render
function assigned to variable then all this code works as expected. This also can't explane using hoisting definition, as first function was not assigned to variable:
function render() {
//returns execution result
return 1;
}
console.log(render()); //returns 1
var render = function () {
return 2;
}
I totally understand that this is buggy code, but I want to understand why this works this way and how not save time with identifying such kind of problems?