One of my friends was taking an online quiz and he asked me this question which I could not answer.
var global = false;
function test() {
global = true;
return false;
function global() {}
}
console.log(global); // says false (As expected)
test();
console.log(global); // says false (Unexpected: should be true)
If we assume that functions are hoisted at the top along with var variables, let's try this one.
var foo = 1;
function bar() {
return foo;
foo = 10;
function foo() {}
var foo = 11;
}
bar();
console.log(foo); //says 1 (But should be 11) Why 1 this time ??
Here is a JSBin Demo and JSBIN Demo2 to play with.
PS: If we remove function global() {}
from test()
, then it runs fine. Can somebody help me understand why is this happening ?
Variables defined with let and const are hoisted to the top of the block, but not initialized. Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared. Using a let variable before it is declared will result in a ReferenceError .
The scope of a variable is the region of your program in which it is defined. 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.
In JavaScript, hoisting is only done for variable and function declarations but not assignments. So, when a variable is assigned then hoisting doesn't work and gives a TypeError or a ReferenceError.
Specifically, we discussed how hoisting allows you to refer to JavaScript variables and functions prior to their declaration, and how closures allow you to access function-scoped variables outside of that specific function.
var
statements and function declaration statements are "hoisted" to the top of their enclosing scope.
Therefore, the function global(){}
in your function creates a local global
name.
Assigning to global
inside your functions binds to this local name. Here's how you can "rewrite" it using hoisting to understand how the compiler sees it:
function test() {
var global = function() {}; // hoisted; 'global' now local
global = true;
return false;
}
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