简体   繁体   中英

How does this js code work?

 var foo = 1; function bar() { foo = 10; return; function foo() {} } bar(); console.log(foo); 

I don't understand why this code outputs 1

Inside of your function bar, you are defining a function foo that will be defined hoisted inside of your function, which means the body of your function is pretty much like:

function bar() {
  function foo() {}
  foo = 10;
  return;
}

This function is scoped inside of the body of bar so it's pretty similar to

function bar() {
  var foo = function foo() {};
  foo = 10;
  return;
}

This means that when you're modifying foo , you're not modifying your global var but only the one scoped inside of bar .

Function declarations:

  • Are hoisted
  • Create a local variable (just like var ) with a matching name

So function foo creates a local variable foo before foo = 10 overwrites it with a number.

Since the variable is local, nothing inside the function touches the global variable which is also called foo so it is set to 1 on line 1 and never changes.

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