I was reading about JavaScript scopes and Hoisting. I saw a sample as below that made some doubts on my mind. So, I was wondering how it works.
var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a);
The code will alert 1 ! But if we eliminate the "function a(){}" part, the code will alert 10.
So, how does it works! What the "function a(){}" is doing here and how it affects the Scopes.
I also Can't understand the meaning of an empty "return;" in this code.
So, how this code works relying the JavaScript Scopes?
In JavaScript, scopes are created by code blocks, functions, modules. While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules. Scopes can be nested. Inside an inner scope you can access the variables of an outer scope.
JavaScript has 3 types of scope: Block scope. Function scope. Global scope.
JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Global variables can be accessed and modified anywhere in the program. Local variables cannot be accessed outside the function declaration. Global variable and local variable can have same name without affecting each other. JavaScript does not allow block level scope inside { } brackets.
First up, an "empty" return;
statement simply exits the function at that point, returning undefined
. It is equivalent to return undefined;
.
The simple case, if you eliminate the function a(){}
part, is that the b()
function changes the global variable a
to be 10
, so then when you alert the value of a
after running the b()
function it is 10
. Without that inner function, all references to a
mean the global variable.
But with the function a(){}
part, that function is declared inside b()
. It is local to b()
. So then you have two different a
s: the global variable, and the local one in b()
. Regardless of where within the containing function another function statement appears, it is treated by the JS compiler as if it is at the top of the function. So even though the function a(){}
line is at the end of the containing b()
function in effect what happens when the code runs is the following:
var a = 1; // declare a global variable a function b() { function a() {} // declare a local function a a = 10; // update local a to be 10 instead of a function return; } b(); alert(a); // show value of global a, which is still 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With