简体   繁体   中英

Why 10 is printed on this javascript snippet hoisting question

Good day everyone. I've been mastering javascript behavior since the pandemic. I already know about hoisting but the other day I saw a guy posted this code snippet to a group

var foo = 1

function bar(){

    if(!foo){
       var foo = 10
    }

    console.log(foo)
}

bar()

This code snippet prints 10!

I'm aware that var declaration is only hoisted not the initialization and that the assignment of 10 will never happen because !foo is false here

So why on earth this prints 10? Please enlighten me

Since var is hoisted a variable named foo is declared inside the function and masks the global variable with the same name.

At this point it has not been assigned a value so it is undefined .

When we reach the second line of the function, the if statement triggers because !undefined is true so line 3 assigns 10 to it.

Line 6 then logs it.

I read a few times that this is an actual interview question on a piece of paper. If so, just tell the guy that it can actually also print 1 .

 var fоo = 1 function bar(){ if(.foo){ var foo = 10 } console.log(fоo) } bar()

Not a serious answer.

In JavaScript function and variable declarations are hoisted at the top of the execution context. You need to remember these three rules for on the same.

  1. variable and function declaration are hoisted at the top of the execution context.
  2. Only declaration gets hoisted, assignments does not get hoisted. Assignment happens where variable was declared.
  3. function declaration has a precedence over variable declaration in the hoisting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM