Javascript Odd Scoping Behavior

I've been going through Javascript function scope and have run into this:

var scope = "global";

function f(){
    console.log(scope);

    var scope = "local";

    console.log(scope);
}

f();

Now I understand that the output of the first log is "undefined" because of how js hoists variables at the top of the function. BUT when I remove var from "var scope = "local";" the first log outputs "global" and this has got me scratching my head. Can someone explain why that is happening please? I mean doesn't js sequentially run the code? As such how can removing VAR have any impact on the first log?

Upvotes: 2

Views: 426

Answers (3)

Remigius Kijok
Remigius Kijok

Reputation: 225

If you omit the var statement, the first log uses the global variable, which is set with the string "global". There is no other local variable and no hoisting.

  1. First log: global variable scope set with "global" content
  2. Assignment of new string for the same global variable
  3. Second log: global variable scope set with "local" content

Upvotes: 1

user2468852
user2468852

Reputation: 118

Javascript sometimes behaves a bit differently from other languages. Take a look at http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html, they explain it a bit.

Upvotes: 1

Marc B
Marc B

Reputation: 360672

Two-pass parsing. The code will be treated as if it was

function f() {
   var scope;  // var created, but no value assigned. this overrides the earlier global
   console.log(scope);
   scope = 'local';
   console.log(scope);
}

The var's CREATION will be executed as if it was the very first bit of code executed in the function. But the actual assignment operation won't occur until where it normally would.

Upvotes: 2

Related Questions