This scenario involves a mix of variable scope and the way functions and variables are defined within a function.
By declaring a local function named a
inside the b
function, you essentially create a new variable within that function that takes precedence over any global variable with the same name.
No matter where a local variable or function is declared within a function, it will be created before the function's code executes. So, in the given example:
function b() {
a = 10;
return;
function a() {}
}
is essentially equivalent to:
function b() {
var a = function(){};
a = 10;
return;
}
When the value 10
is assigned to the variable a
within the function, it replaces the local function with the number. In JavaScript, functions can be treated as first-class citizens, allowing them to be passed around like other values and replaced by different values.
Since the function only modifies the local variable a
, the global variable a
remains unaffected.