2

I've come across this snippet and I have no idea why it does what it does. Try to answer the question yourself before looking at my answer below the code: what number will this alert?

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

My guess was that this would alert the number 10.. I was wrong. It alerts 1. Why? I'd've thought that "function foo()" won't be even considered, as there's a return keyword before. And even if, it's inside a bar() function scope. I assume that there's some hoisting going on in the background. Can someone explain please?

wood1y
  • 189
  • 1
  • 7
  • 2
    I would guess that the `foo` function is hoisted up to the top of `bar()`, creating a local `foo` variable, `foo = 10` then overwrites that local var of the function, leaving the external foo intact. Would be easier to test by stepping through a debug, but that's my guess – MDEV Oct 24 '15 at 14:00

0 Answers0