Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Else VS Multiple If Statements [duplicate]

Tags:

java

javascript

c

I always use multiple if statements when coding:

if(logicalCheck){
  ...
}

if(secondLogicalCheck){
  ...
}

and rarely use If Else. I understand that using my way means that more than one of my logical checks can be fulfilled and only one in an if else chain can occur.

My question is, is there any performance benefits in using one method over the other in C, Java or JavaScript? Is there anything particular wrong with using multiple if statements?

like image 490
Haych Avatar asked Dec 18 '22 22:12

Haych


1 Answers

Using only if, interpreter or whatever will test all conditions but if you use else if (if possible) then on passing any condition , next else if will not be tested or checked.

if (age < 10){
   // do something
}
if (age < 20 && age > 10){
   // do something
}
if (age < 30 && age > 20){
   // do something
}

All conditions will be tested/compared

but in this scenario

if (age < 10){
   // do something
}
else if (age < 20 && age > 10){
   // do something
}
else if (age < 30 && age > 20){
   // do something
}

if age is 5, only first condition will be tested.

like image 95
Zohaib Ijaz Avatar answered Dec 29 '22 00:12

Zohaib Ijaz