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
  • 18,353
  • 26
  • 83
  • 127
  • 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
  • 311,322
  • 76
  • 447
  • 566
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
  • 223,102
  • 54
  • 301
  • 354
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 is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
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
  • 24,338
  • 12
  • 50
  • 71