3

I understand the following function because variable hoisting happens. foo();

function foo() {
    console.log( a ); // undefined
    var a = 2;
}

However what I don't understand is the following part. I got Reference Error, why?

foo()
function foo() {
    console.log( a ); // Reference Error
    a = 2;
}

--- Edit ---
So far, what I understand from the answers is the second does not make any hoisting and we cannot use any undefined variable.

foo()
function foo() {
    //  we cannot use any undefined variable, which "a" here 
    console.log( a ); 
    window.a = 2;
}

For example

var a;
a; //undefined
b; //Reference error
allenhwkim
  • 27,270
  • 18
  • 89
  • 122
  • 2
    As there is no `var` declaration, it'll not be hoisted, and it is defined in Global space **after** log statement, so throwing error – Tushar Dec 03 '15 at 03:31
  • What else would you have expected? – Bergi Dec 03 '15 at 03:33
  • 1
    @Bergi `undefined` _maybe_ – Tushar Dec 03 '15 at 03:33
  • 1
    @Bergi I don't think the _so dupe_ answers the question, that is related to Global/Local scope, this is related to hoisting. – Tushar Dec 03 '15 at 03:37
  • @Tushar: Do you think [this](http://stackoverflow.com/a/9981152/1048572) would be a better dupe? – Bergi Dec 03 '15 at 03:44
  • @Bergi, if you think this is dupe and better to be removed, I will delete it. I got good anderstanding from Tushar, thanks to him – allenhwkim Dec 03 '15 at 03:52
  • Main thing to note here is that **variables declared without `var` are not hoisted**, and an undeclared variable throws Reference Error. – Tushar Dec 03 '15 at 03:54
  • @allenhwkim: No, closing doesn't mean that it's better to be removed, please keep it. It just seemed to already be answered there, at either of the two linked questions. – Bergi Dec 03 '15 at 03:54
  • @Tushar: You meant to say "variables *defined* without `var` are not *declared*"? :-) – Bergi Dec 03 '15 at 03:55
  • @Bergi No, I'd say this question should not be removed, this'll help peoples understand why the code is working like this and will avoid asking same question in future. – Tushar Dec 03 '15 at 03:56
  • @Bergi _"variables defined without var are not declared"?_, I said **hoisted** :) – Tushar Dec 03 '15 at 03:57
  • @Tushar: I see what you've said, I was just nitpicking that a variable without `var` is not *declared* (unless it's a function, parameter etc) - and are not hoisted either, of course. – Bergi Dec 03 '15 at 03:59
  • @allenhwkim: No, it's not the function call that throws the `ReferenceError`. It's the expression `a` or `b` itself that throws when evaluated - try `a; b;` (without any `foo(…)`) – Bergi Dec 03 '15 at 04:02
  • Thanks @Bergi, edited it. – allenhwkim Dec 03 '15 at 04:22

1 Answers1

0

In the first one, a is declared, but undefined, in the second it's also also undeclared (can't be found in foo or in global scope), so throws a ReferenceError.

Hunan Rostomyan
  • 2,176
  • 2
  • 22
  • 31