Writing stylish JavaScript instead of if-then branches

advertisements

How can I make the following code more elegant and readable?

if (this.flag === 1) {
  this.value -= 0.1;
}
if (this.value <= 0) {
  this.flag = 0;
}

if (this.flag === 0) {
  this.value += 0.1;
}
if (this.value >= 1) {
  this.flag = 1;
}

Edit: Let's say, for simplicity's sake, I'm changing the opacity of an object, and I want it to fade in and out from 0 to 1 over and over inside some sort of loop. .value is the opacity, and .flag is to tell it when to switch directions.


You could simplify some if-else scenarios with shorthand notations like below.

this.flag = this.value <= 0 ? 0 : 1;
this.value = this.value + (this.flag === 1 ? -0.1 : 0.1);

However, your script, in its current form, uses exclusive if conditions that don't cover all possible values of flag and value with an else block. Depending on whether you care about that, my proposal above could break your code.


EDIT - based on OP updates

flag should be a boolean true/false.

this.flag = this.value > 0;
this.value += (this.flag ? -0.1 : 0.1);


EDIT 2 - based on comments

Why should this.flag be manipulated through the value of this.value? The flag should be controlled through other means such as a checkbox or something, so your opacity change script should really be just this:

this.value += (this.flag ? -0.1 : 0.1);

If you're trying to auto-toggle the flag when the opacity reaches 0 or 1, you can do this:

this.value += (this.flag ? -0.1 : 0.1);

if(this.value === 1 || this.value === 0) {
  this.flag = !this.flag;
}

Please note that this answer has already drifted outside of the scope of the question, which was to have a more elegant approach to conditionals. You'd be better off asking a new SO question if you need to discuss any further.