Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsLint 'out of scope' error

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.

like image 871
Rajat Avatar asked Mar 20 '10 23:03

Rajat


People also ask

What is out of scope error?

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).

What does it mean when something is used out of scope?

In project management, “out of scope” means anything that is outside the parameters of an initiative. At the beginning of a project, the scope is established in documents like the scope statement. It clarifies the work and deliverables of a project, setting out the expectations for both parties.

Was used before it was defined JSLint?

The "'{a}' was used before it was defined" error (and the alternative "'{a}' is not defined" error) is thrown when JSLint, JSHint and ESLint encounter an identifier that has not been previously declared in a var statement or function declaration.


1 Answers

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;     // … } 
like image 82
Quentin Avatar answered Sep 22 '22 13:09

Quentin