user2952265 user2952265 - 1 month ago 19
Javascript Question

What creates a function in a function?

Why is the result of the following code 1 and not 10? Why doesn't the function bar() change the value, even though there is a return statement.

var foo = 1;
function bar() {
foo = 10;
return;

function foo() {}
}

bar();
alert(foo);

Answer

This is because function definitions are hoisted to the top of their scope, so the foo assignment inside bar() is actually referring to the local function that has an empty body.

You can read more about this here

Comments