0

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?

NorCalKnockOut
  • 870
  • 3
  • 10
  • 26
  • 1
    possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – baao Sep 29 '15 at 15:53
  • No more harm than other global variables… – Bergi Sep 29 '15 at 15:57

1 Answers1

1

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • The variable is global only for the file though right? – NorCalKnockOut Sep 29 '15 at 15:57
  • 1
    @NorCalKnockOut: No, typically not. If it's a module (in node.js or so), yes it's local to that module, but in browsers a global variable is global to the window. – Bergi Sep 29 '15 at 15:58
  • I also find it useful sometimes as an indicator of whether a function needs to be broken down some (along with the number if lines it covers). If there are loads of var declarations at the head of a function, it might be worth taking a look a refactoring. Not always, but sometimes it can be useful. – Andy Sep 29 '15 at 15:59
  • This is why it is a common practice to wrap scripts intended to run in a webpage in an IIFE - so they don't use any globals. – Quentin Sep 29 '15 at 15:59
  • Okay thanks. I have around 10-15 variable declarations at the top of a js file. Maybe I can look at refactoring it. – NorCalKnockOut Sep 29 '15 at 16:00