0

I am trying to create an if statement that it uses multiple success case. For example if the first branch is success, it has to still check the second branch, maybe that turns success as well. in the following code, the statement exists once it success in the first branch. I want it to go trough and check the next one as well.

var branch1 = true;
var branch2 = true;

if(branch1 === true){
 console.log("branch1");
}
else if(branch2 === true){
 console.log("branch2");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

So my ideal respond for the above code would be branch1, and branch2 as well. I might add more than two branches.. but I simplified it here. Any idea?

Thanks

DannyBoy
  • 434
  • 5
  • 21

3 Answers3

4

Just remove the word "else"

if(branch1 === true){
    console.log("branch1");
}
if(branch2 === true){
    console.log("branch2");
}
Lokkesh
  • 550
  • 3
  • 11
1

Simple add branch to an array and loop :

var branchs = [true, true, true, true, true, true];

for(var i in branchs){
  if(branchs[i] === true){
    console.log("branch"+i);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1

Even you don't need to use the === operator.

var branch1 = true;
var branch2 = true;

if(branch1) { console.log("branch1"); }

if(branch2) { console.log("branch2"); }
Harish
  • 462
  • 6
  • 13
  • 1
    why using === cos == is the evil ... https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons here the creator of Javascript Douglas Crockford talk about this too https://softwareengineering.stackexchange.com/questions/268124/does-using-in-javascript-ever-make-sense/268157 –  Sep 10 '17 at 18:39
  • 1
    Yes, That's correct. But what if we only need to check if a variable holds true or false in that case do we really need === or == – Harish Sep 11 '17 at 02:13
  • 1
    yes that's true in this example that no really important part, but in the real live this is your evil talk about this to a sysadmin or operator system from hosting company :). –  Sep 11 '17 at 09:35