Variables Scope – Should I Declare Variables at the Top of the Function for Reasons Other Than the Scope Rules?

scopevariables

In JavaScript, one should declare all variables at the beginning of the function to mitigate the risk of mistakes related to the fact that the scope of variables is a function. The following code illustrates this non-intuitive scope by actually printing "Hello, World" to the console:

var demo = function () {
    if (false) {
        var hello = "Hello, World";
    }

    console.log(hello);
};

Similarly, in VB6 (but not in VB.NET), the variables have a scope of a function/sub, which also means that they would better be declared at the top of the function/sub block.

C, C++, Java, C#, Python or PHP don't have any reason to move the declaration of variables to the top of the method/function: instead, variables are preferably declared close to the location where they are used.

Are there languages where it is better to declare the variables at the top of the function-type block (instead of declaring them as close as possible to the location where they are used) for a reason other than function-level scoping?

In other words, is the non-intuitive scoping similar to the one used by VB6 and JavaScript the only reason to move the declaration of variables at the top of a function?

Best Answer

Each computer language has its strengths and pitfalls. Each has its own coding standards/practices often accepted, built and dictated by the community around it. Because programming is a precise art I would say, unless there is a good reason to do something, you shouldn't.

Now there are very good reasons to declare variables close to where they are used:

  • Makes it easy to determine the type, when reading code.
  • Makes it easy to delete code including the declaration all together.

But as you suggest, for some languages there are better reasons to not do that, for sake of clarity or scope. Another reason could be to reserve memory or registers early on, again it depends on the language you are using. A new language may come along with non-C like semantics and may require a different approach to where variables get declared.

I would also always recommend following the coding standards established by the community for your language of choice.