28
function test(){
    if(true){
        var a = 5;
    }
    alert(a);
}

test();

I keep getting 'out of scope' errors in my JS code when I check with JsLint which make no sense to me.So I quickly created an example. Is there something actually wrong with this code piece, as the variable is eventually hoisted to the top of the function anyways.

Rajat
  • 32,970
  • 17
  • 67
  • 87
  • 3
    Many of JSLint's "errors" are really just warnings in the sense that they aren't JavaScript language errors and won't necessarily fail at runtime. They're called errors because Douglas Crockford considers them to be bad practice. – Max Nanasy Dec 07 '12 at 03:04

3 Answers3

34

While var localizes a variable to the function and is subject to hoisting, most languages have block scope and not function scope.

By using the var keyword inside an if block, but accessing the variable outside that block, you've created a construct that can be confusing to people not familiar with that JS idiosyncrasy.

Douglas Crockford recommends using a single var statement at the top of a function that specifies all the variables that should be scoped to that function.

function test(){
    var a;
    if(true){
        a = 5;
    }
    alert(a);
}

test();

With multiple variables you would have:

function foo () {
    var a, b, c, d = "only d has an initial value", e;
    // …
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 15
    Douglas Crockford recommends *a lot* of things ... as with any tool you should always take JSLint's recommendations with a grain of salt, and tailor them to you/your team. If everyone on your team understands how JS variable scoping works, by all means you should ignore Crockford's recommendations on where to put your "var" statements). – machineghost Nov 16 '12 at 01:29
5

The code that you wrote is working. It is just not very readable/maintainable. Declaring the variable a inside the scope of the if may give the false impression that a is only visible inside this scope (which, as this program shows, is not true - a will be visible throughout the whole function).

This JsLint warning encourages you to place the declaration at the exact scope where the variable is actually used, as follows:

function test(){
  var a;
  if(true){
      a = 5;
  }
  alert(a);
}
Itay Maman
  • 30,277
  • 10
  • 88
  • 118
1

Javascript have function scope and not block scope. So, variables declared inside if function is visible and accessible outside the if block and within the function in which if statement is declared.

Online compilers like JSLint and jsbin give warnings but they are not errors.

kumarras
  • 116
  • 5