0

I am not understanding this - how can a var that's defined within an if condition be used outside of that condition?

Example JS:

if (1===2) {
  var myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);

Renders: myVar = I live in brackets

Isn't myVar's scope only inside of that if (1===2) condition?

Ian Davis
  • 19,091
  • 30
  • 85
  • 133
  • In javascript, scope is by function. `if(){}` does not have its own scope – Sharlike Feb 28 '13 at 19:17
  • MDN is a great resource for learning javascript: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Variable_scope – jholloman Feb 28 '13 at 19:19

4 Answers4

2

Scopes only apply to functions, not other blocks.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

Javascript does not have block scope, it only has function scope.

In other words, variables declared by var are accessible within the scope of a function, everywhere, just there, not outside.

jAndy
  • 231,737
  • 57
  • 305
  • 359
1

Because of hoisting, every variable declaration pops to the top of the function scope.

alert(foo); // undefined (no error because of the hoisting.)
var foo = 2;
alert(bar); Error
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • but, I don't have any functions on the page. in that case, does JS just treat this all as under the umbrella of one wrapper function? – Ian Davis Feb 28 '13 at 19:18
  • 1
    @IanDavis, if it's not in a function it's inside the global object. – gdoron Feb 28 '13 at 19:20
0

When a javascript variable is defined, the declaration is hoisted to the top of the function scope.

So this:

if (1===2) {
  var myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);

is equivalent to this

var myVar;
if (1===2) {
  myVar = "I live in brackets";
}
$("#debug").append("myVar = " + myVar);
$("#debug").append("but I'm about to throw a 'not defined' exception right... now " + firstAppearanceVar);

Any variable defined in a function therefore, is accessible anywhere in that function, or inside any inner functions. They are not accessible outside the function.

so

(function(){
    if (1===2) {
      var myVar = "I live in brackets";
}}())
$("#debug").append("myVar = " + myVar); //reference exception
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71