Multiple declaration of variables in Javascript

7

It has become quite common to declare variables in multiple lines in JavaScript. Primarily, when they are initialized later:

var var1 = null,
    var2 = null,
    var3 = 0;

The "normal" would look like this:

var var1 = null;
var var2 = null;
var var3 = 0;
  • Why has multiple declaration of variables in multiple lines become so common?
  • What are the differences between the two?
  • When should I use one or the other?
asked by anonymous 15.11.2014 / 05:09

2 answers

8

It's mostly a matter of style, a matter of taste. There is no difference in functioning between the two.

The only benefit of declaring with commas is to save a few bites because you do not need to use var so many times and thus make the script slightly smaller. To save such bites you should do this inline , on the same line as the

    

15.11.2014 / 08:53
5

There are many arguments in favor of both sides, ranging from automatic insertion of semicolons, hoisting and readability to "this is easier to do diff than that".

It all comes down to Choose what's best for you .

There is, however, an objective criterion that can make you choose to declare a single var , which is performance. In fact, the performance of the declaration of a single var is greater than the declaration of multiple var as indicated by the following tests:

It may be a small and irrelevant difference, but it is the only criterion that goes beyond subjectivity.

    
15.11.2014 / 15:02