While I was reading about Javascript hoisting, I tried the following. I am not sure why the first one and second one output differently. Thanks in advance. (I am not even sure that this is related to hoisting. )
var me = 1;
function findme(){
if(me){
console.log( me );//output 1
}
console.log( me ); //output 1
}
findme();
However the followings output undefined.
var me = 1;
function findme(){
if(me){
var me = 100;
console.log(me);
}
console.log(me);
}
findme();
// undefined
Hoisting in JavaScript is the behavior by which the declaration of variables and functions are moved to the top. This means that the variable or function declaration need not be done before initializing and calling them. Hoisting will happen only if var is used for declaration and not with const or let declarations.
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared.
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 .
In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
Variable declarations get hoisted to the top of every function, but the value assignments stay where they are. So the second example is run like this:
var me = 1;
function findme () {
var me; // (typeof me === 'undefined') evaluates to true
if (me) { // evaluates to false, doesn't get executed
me = 100;
console.log(me);
}
console.log(me);
}
findme();
The declaration of thee local variable in the if
block in the second example is hoisted to the entire function.
Thus, me
in the function always refers to the local variable, not the global.
However, the value of the variable is not hoisted, so it's always undefined
and the if
is never entered.
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