-1

I was running following JavaScript:

var foo = function() {
  var a = 3,
      b = 5;
  var bar = function() {
    var b = 7,
        c = 11;
    a += b + c;
    console.debug(d);
  };
  bar();
  console.debug(c);
  var d = 10;
};
foo();

Clearly, d is not known to nested function bar and c is not known to external function foo. But in developer tools, when I load my web page I get two different logs one by one:

undefined
Uncaught ReferenceError: c is not defined

Why are the errors different for the two cases? In my opinion both should have thrown simply thrown reference error if the corresponding variable is not known to them or is out of scope.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
RBT
  • 24,161
  • 21
  • 159
  • 240
  • because `c` is in the function scope. Anything declared with `var` is not available outside the function. It is only available inside of it. – epascarello Apr 27 '17 at 02:09
  • Look at: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – epascarello Apr 27 '17 at 02:13
  • and http://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting – epascarello Apr 27 '17 at 02:14
  • 2
    The dupe should explain it. [Var hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) happens and `d` is actually declared but not initialized with a value at the beginning of the function because `var`s are functions scoped. Thus, you get undefined instead of a reference error for `d` inside `bar`. But since `c` only ever existed in `bar`, it's never accessible outside. – Andrew Li Apr 27 '17 at 02:17

1 Answers1

0

The variable c died when function foo returned; c is local to bar because a var qualifier was used.

ncmathsadist
  • 4,684
  • 3
  • 29
  • 45
  • But variable `d` has been declared after the definition of function `bar` completes. So `d` should be equally dead (not have come to life yet) for `bar` function. Isn't it? I've *not* downvoted you. – RBT Apr 27 '17 at 02:16
  • This answer is really incomplete to the issue at hand. It doesn't address the main issue. – Andrew Li Apr 27 '17 at 02:18
  • `d` is not dead because of hoisting. – ncmathsadist Apr 28 '17 at 15:13