Pattu
Pattu

Reputation: 3809

Multiple variable declaration in one line - Javascript

I am trying to learn Javascript. I came across the following code.

// Random function.
function order_summary(order_object) {
  var x, y;
  // More code here.
}

When I run this code in Jslint, it's giving me the following error.

Expected ';' and instead saw ','.
var x, y;

I don't see any problems with this code. Can anyone explain what this error means?

Upvotes: 1

Views: 4323

Answers (3)

itsme_seenu
itsme_seenu

Reputation: 340

It is not a problem at all to declare multiple variables using single var in any javascript run-time. This is just a warning thrown by JSLint as by default it is recommending 1 var per line.

If you check the option "multiple vars" under "Tolerate.." this warning will be ignored.

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

There is one very important difference between the two styles:

var l1 = 1,
    l2 = 2;

and

var l1 = 1;
var l2 = 2;

Namely: In the second form the debugger can step through each assignment one-by-one.

In the first form, the entire line is one massive expression and the debugger tries to execute it at once. When you have assignments that depend upon earlier operations, the line-by-line approach is very useful.

Upvotes: 3

derp
derp

Reputation: 2308

Jslint is a sort of a style enforcement tool and doesn't like having multiple variables declared on one line. To fix it, simply declare each variable on each line. e.g.

var x;
var y;

The reason why jslint doesn't like this is because javascript has semicolon insertion. So if you accidentally omit a comma like this:

var x
y = 10;

JS will insert the semicolon at the end of the first line and you would have accidentally created a global variable y.

Upvotes: 3

Related Questions