NorCalKnockOut
NorCalKnockOut

Reputation: 878

Declaring variables at top of js file

I have been declaring variables I use in multiple functions at the top of the file.

var a;

window.onload = function() {
   a = 10;
}

function bar() {
  if(a > 5)
    //do something
}

This may be a bad example, but the question is does declaring variables at the top of the file harm anything?

Upvotes: 0

Views: 1511

Answers (1)

Quentin
Quentin

Reputation: 943614

Declaring variables at the top of the function they should be scoped to (which is the top of the file for globals), is a common practice used to:

  • Avoid confusion new developers experience when encountering hoisting
  • Make it clear which variables are scoped where to developers reading the code (but putting them all in one place per scope).

It doesn't introduce any problems (beyond altering the way you have to clean up old code when you stop using a variable).

Upvotes: 2

Related Questions