yokimoto
yokimoto

Reputation: 40

operator += producing unexpected result javascript

function range(start, end, st) {
  var arr = [];
  var counter = start;
  while (counter <= end) {
    arr.push(counter);
    counter += st || counter + 1;

  }
  return arr;
}

console.log(range(1, 10));

this produces unexpected result

however this:

counter = counter + st || counter + 1;

produces the expected result any idea why?

Upvotes: 0

Views: 88

Answers (2)

melpomene
melpomene

Reputation: 85767

The difference is that

counter += st || counter + 1;

means the same as

counter = counter + (st || counter + 1);

whereas counter = counter + st || counter + 1 means counter = (counter + st) || (counter + 1).


In your example code st is undefined, so the loop effectively does

counter += counter + 1;

every time, which is equivalent to

counter = counter * 2 + 1;

Hence the large skips.


On the other hand, in

counter = counter + st || counter + 1;

st being undefined means counter + st is NaN, which counts as false, so this effectively runs

counter = counter + 1;

which is equivalent to

counter += 1;

However, this only works by accident. If you call your function with different arguments, such as:

function range(start, end, st) {
  var arr = [];
  var counter = start;
  while (counter <= end) {
    arr.push(counter);
    counter = counter + st || counter + 1;
  }
  return arr;
}

console.log(range(-2, 2, 2));

The result is [ -2, -1, 1 ] instead of the expected [ -2, 0, 2 ].


You can fix your code by doing

counter += st || 1;

instead.

Upvotes: 1

JJJ
JJJ

Reputation: 33163

I'm not sure what you expect the code to do, but counter += st || counter + 1 is equivalent to

counter += (st || (counter + 1));

which is equivalent to

if(st) {
    counter = counter + st;
}
else {
    counter = counter + counter + 1;
}

On the other hand counter = counter + st || counter + 1 is equivalent to

counter = (counter + st ) || (counter + 1);

which is equivalent to

if(counter + st) {
    counter = counter + st;
}
else {
    counter = counter + 1;
}

So they do quite different things. I assume the operator precedence is throwing you off.

Upvotes: 2

Related Questions