5

We're working with a new company and they have a coding standard where they declare all Javascript variables used in a method immediately in the first line of the method.

I asked if there was a reason they did this and was simply told it was their coding standard, so I googled and apparently it is indeed a recommended standard according to some sites.

My first thought is that if a method is so big that you actually find it helpful to put all variables at the top then your method is too big and needs to be broken up.

So my question is, what is the purpose of declaring the variables at the top as opposed to declaring them when they are first used? Is it just a coding standard designed to help people who write methods that are (in my personal opinion) too long as I presume, or are there other benefits I'm overlooking?

3
  • all vars on one line, all vars the top, one var per line, vars at the point of usage are all 100% style and therefore opinion. Scoping rules, const, let all have nothing to do with it. It's a choice, that's it. Commented Feb 17, 2019 at 6:34
  • 2
    @gman const variables cannot be declared without also assigning a value to them, so declaring variables all at once at the top before starting to assign to them and do things makes the use of const impossible. (of course, one is free to not use const at all, if one wishes, but that doesn't mean they have nothing to do with each other) Commented Feb 17, 2019 at 6:39
  • Sure const and let have more restrictive uses than var, but whether to use var vs let or var vs const is entirely a style choice. I choose to never var and I choose to always declare as close as possible to usage. That doesn't mean it's not a style choice. Proof that you can use var anywhere is the fact that the transpilers all compile to nothing but var taking the appropriate precautions to make sure the semantics are the compatible. This question should be closed as "primarily opinion based" ... in my opinion Commented Feb 17, 2019 at 8:55

2 Answers 2

6

It used to be a method to make code clearer, back when we only had var, which gets hoisted. For example, the following is a pretty common error you still see nowadays:

for (var i = 0; i < arr.length; i++) {
  arr[i].addEventListener('click', function() {
    console.log(i);
  });
}

If a coding style or a linter required the var i to be extracted out of the loop and declared at the top of the function, it becomes clearer that there's only one binding of i, and that by the end of the loop, i === arr.length, possibly prompting the coder to fix the logic error before having to run it at all:

var i = 0;
for (; i < arr.length; i++) {
  arr[i].addEventListener('click', function() {
    console.log(i);
  });
}

But now that we have const and let, which are not hoisted out of loops (they have block scope, not function scope), the manual hoisting of the variable declarations to the top of the function has much less utility.

Some might argue that manually hoisting variables to the top of their scope makes things worse nowadays, if one accepts that const is strongly preferable to let (const variables cannot be reassigned; let variables can, making const variables easier for a programmer to internalize while reading code). For example, imagine having variables that depend on the value of other variables: refactoring the following

var startingNum, numMultipliedByTwo, plusOne;
startingNum = 2;
numMultipliedByTwo = startingNum * 2;
plusOne = numMultipliedByTwo + 1;

to ES6+, with manual hoisting, could only be done with let:

let startingNum, numMultipliedByTwo, plusOne;
startingNum = 2;
numMultipliedByTwo = startingNum * 2;
plusOne = numMultipliedByTwo + 1;

But since let doesn't have the same hoisting problems that var does, and since const is preferable to let, one may well conclude that this sort of style doesn't provide any benefit, and instead use:

const startingNum = 2;
const numMultipliedByTwo = startingNum * 2;
const plusOne = numMultipliedByTwo + 1;
Sign up to request clarification or add additional context in comments.

2 Comments

@D_N Yep, but that's what Babel is for. Best to write in the latest and greatest version of the language, to make code easy to read and write, and transpile down to ES5 for crappy ancient browsers in production
@D_N That was my first thought but then I also quickly found Babel as CertainPerformance mentioned. Although again, it's my personal opinion that Babel shouldn't even be needed 99.9% of the time anyway (for this particular issue) if you keep your methods short.
-2

It is very good to sum all your variable at someplace, it easer to understand what variable exist at the begning of your functions.

Say you have two variable in a very very big function. User and Role

the first thing you will see those variable and you know they are available to the user across all your function, and you could call them a global variable in the function.

and then you have the let variable that exist only at someplaces like this for example

var item;
for (var i = 0; i < arr.length; i++) {
  item = arr[i];
  let x = arr[i]; // this will work.
  item .addEventListener('click', function() {
    var subItem = arr[i]; // this wont work. 
    var subItem = item; // this wont work either
    var subItem = x; // this will work.
  });
}

So the company policy is only good when it come to global variable cases(in the function). You should try to follow them. But programming is a personal thing, so be wise about what to use in each context and try to understand what each case needs.

2 Comments

It's an opinion on whether or not declaring variables in one place at the top is good. Google does not follow that policy. I suspect their programmers are not bad and they choose not to put variables at the top. You can disagree with their policy, just pointing out there is no objective reason it's "good to sum all your variables at someplace"
Yepp and this is what i said, and also wanted to point out that its not always right. it all depend on in what context the variable will be available in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.