0
function foo(a) {
  function a() {
    return 8;
  }
  return a();
  y = 9;
}
console.log(foo() + " " + y);

This gives an undefined error for variable y.

function foo(a) {
  y = 9;

  function a() {
    return 8;
  }
  return a();
}
console.log(foo() + " " + y);

This prints 8 9 in the browser console.

If we declare a variable without the var keyword than it becomes global variable.

Why first function does not follow the idea?

jwpfox
  • 5,124
  • 11
  • 45
  • 42
  • Please do some research before asking a question on Stack Overflow. By _literally_ copy-pasting this question's title in Google, I found the linked duplicate. – Cerbrus Sep 12 '17 at 09:14
  • @Cerbrus it's nothing to do with variable scope and certainly not a duplicate of that. – MrCode Sep 12 '17 at 09:18
  • Use strict mode and the second snippet will throw an exception as well. Don't not use `var`, just use `var` in the appropriate scope! – Bergi Sep 12 '17 at 09:23

1 Answers1

0

It's because in the first example, you have a return statement before the y = 9 and so the assignment is never reached, leaving it undefined.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Please don't answer obvious duplicates like these. Don't encourage or reward users for doing _no_ research whatsoever. – Cerbrus Sep 12 '17 at 09:16
  • @Cerbrus it's not a duplicate of that. – MrCode Sep 12 '17 at 09:19
  • 1
    Then it's a dupe of [this](https://stackoverflow.com/questions/14102912/execute-statement-after-return-statement-in-javascript). My point is that the OP should really do some research before asking. – Cerbrus Sep 12 '17 at 09:20