bigtunacan
bigtunacan

Reputation: 4996

JSHint expected an assignment or function call for multiple assignment

I was linting some existing JavaScript and I get the error message Expected an assignment or function call and instead saw an expression. for the following.

var k, i;
k = 0, i = -1;

The assignment appears to happen correctly, so what is wrong with this that it causes the lint warning?


For a bigger picture; here is what the beginning of the function looks like that leads up to this, if it is helpful.

var subgroups = {},
    groupSums = [],
    groupIndex = d3.range(n),
    subgroupIndex = [],
    k,
    x,
    x0,
    i,
    j;

chords = [];
groups = [];

// Compute the sum.
k = 0, i = -1; while (++i < n) {
  x = 0, j = -1; while (++j < n) {
    x += matrix[i][j];
  }
  groupSums.push(x);
  subgroupIndex.push(d3.range(n));
  k += x;
}

Upvotes: 2

Views: 5740

Answers (3)

user663031
user663031

Reputation:

The comma operator creates an expression. It's an operator that evaluates the two things on the left and right, then yields as its value the one on the right. Even if the things separated by the commas are assignments, JS still views the comma operator as creating an expression.

JSLint and JSHint don't like expressions that are just sitting there not doing anything, such as

0 !== 1;

To the linters,

k = 0, i = 1;

is a forlorn expression, not doing anything.

In your particular case, it could be easier to just do

for (k = 0, i = -1; ++i < n; ) {

and be done with it, although personally I'd write

for (k = 0, i = 0; i < n; i++) {

As you probably already know, you can turn this off (examples for JSHint):

/*jshint -W030*/
/*jshint expr:true*/

Upvotes: 6

Tomalak
Tomalak

Reputation: 338406

Use the var keyword and the error goes away. (Turns out the OP did use the var keyword.)

Rolling two separate assignments into one expression with the comma operator like this:

k = 0, i = -1;

is legally possible in JavaScript. It is not considered good style, though. Simply use the semicolon as a statement separator:

k = 0; i = -1;

The comma operator, as per the MDN:

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression.

Your situation does not fit the bill. Clever use of language features is considered harmful. Try not to do clever stuff outside of code golf competitions.

Upvotes: 2

Nicol&#242;
Nicol&#242;

Reputation: 1875

You should do it like this:

k = 0;
i = -1;

Upvotes: -2

Related Questions