Search code examples
javascriptvariable-declaration

What does it mean when the `var` keyword is followed by multiple variable names?


I recently came across the following line of code in a JavaScript book that I am working through:

var col = [], top, bottom;

This is the first time I've encountered a variable seemingly being given three variables. Could someone explain what is happening in this line of code?


Solution

  • It is simply a shorter version of this:

    var col = [];
    var top;
    var bottom;
    

    There is no real advantage/disadvantage of one style over the other, but JSLint likes to have all var declarations in each scope combined (as you have in your question):

    In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function.


    For a full explanation of why this is the case, you can have a look at the ECMAScript spec. Here's the relevant part of the grammar:

    VariableStatement : var VariableDeclarationList ;

    VariableDeclarationList : VariableDeclaration VariableDeclarationList , VariableDeclaration

    VariableDeclaration : Identifier Initialiseropt

    It's also worth noting that the commas used here are not the same as the comma operator. It just happens to use the same character.