Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Questions on Javascript hoisting

Tags:

javascript

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
like image 254
shin Avatar asked Jan 13 '13 01:01

shin


People also ask

What is hoisting in JavaScript interview questions?

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.

What is the use of hoisting in JavaScript?

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.

Which variables are hoisted in JavaScript?

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 .

Is hoisting a good practice in JavaScript?

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.


2 Answers

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();
like image 179
danronmoon Avatar answered Nov 05 '22 16:11

danronmoon


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.

like image 41
SLaks Avatar answered Nov 05 '22 16:11

SLaks