Home > database >  Which if else code should I use, single line or multiple lines?
Which if else code should I use, single line or multiple lines?

Time:01-19

There are two types of if function codes:

condition1 ? function1 : condition2 ? function2 : function3;

if (condition1) {
  function1
} else {
  if (condition2) {
    function2
  } else {
    function3
  }
}

I don't know what is the correct way to use the if else function code, I hope everyone can tell me.

Feel free to leave a comment if you need more information.

Which if else code should I use, single line or multiple lines?I would appreciate any help. Thank you in advance!

CodePudding user response:

Those two are not "different styles of if".

The first one is the ternary operator. As the term operator suggests, it is used to produce a value.

The second one is the flow control statement if. It does not produce any value, it changes your program's flow.

So which one should you use? The one that fits your goal best. Do you need a value? The operator. Do you need to change your program flow? The flow control statement.

Try to reproduce this if statement with a ternary operator:

if (trafficlight.current == red) {
  stopVehicle();
}

You cannot. Not without adding pointless waste. Because this is flow control.

On the other hand, this:

var newSpeed = (trafficlight.current == red) ? 0 : this.MaxSpeed;

Would be very convoluted to write as an if statement. Because it is generating a value.

So pick what is best for your program. It's not a "style" to follow blindly. It is a decision you should make for every one of those instances.

  • Related