Skip to content Skip to sidebar Skip to footer

Javascript, Confusing Syntax When Declaring A Variable

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 se

Solution 1:

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.

Solution 2:

Read it as

var
    col = [],
    top,
    bottom;

Three variables are declared, but only one is initialized.

Solution 3:

This is general syntax of declaring multiple variables in javascript. It says you are declaring three variables namely col , top , bottom , where col is of type array. It's same as :

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

Helpful links : http://docstore.mik.ua/orelly/webprog/jscript/ch04_02.htmhttp://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/declareAnArray.htm

Solution 4:

This statement does not assign three values to col, it simply declares three variables and one of them is an array.

Post a Comment for "Javascript, Confusing Syntax When Declaring A Variable"