-3
var a = 0;
var param = 'add';
while(a < 50){
    console.log(a); //prints out values from 0 to 49
    if(param === 'add'){
        a = a + 1;
    }else{
        a = a - 1;
    }
}

While being very simple and doing its job, I would like to make this code shorter

while(a < 50){
    console.log(a);
    a = a + (param === 'add')? 1 : -1;
}

But a never grows and stays 1. Could anyone explain such behavior?

Keetch
  • 75
  • 1
  • 9

1 Answers1

1

The expression is evaluated as

a = (a + (param === 'add')) ? 1 : -1;

which boils down to

a = 1;

You may solve this by writing

a = a + ((param === 'add') ? 1 : -1);

or even shorter:

a += (param === 'add') ? 1 : -1;
www.admiraalit.nl
  • 5,768
  • 1
  • 17
  • 32