How does this js code work?

  • A+
Category:Languages
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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: