Which one is good to use when there is a large number of branching flow in Node.JS Program.
switch
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
OR
if-else
if (condition1)
{
execute code block 1
}
else if(condition2)
{
execute code block 2
}
else
{
code to be executed if n is different from condition1 and condition2
}
For just a few items, the difference is small. If you have many items you should definitely use a switch. It give better performance than if-else.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if-else where the last item takes much more time to reach as it has to evaluate every previous condition first..
switch(n)
{
case 1,3,4:
execute code block 1
break;
case 2,5,9,10:
execute code block 2
break;
default:
code to be executed if n is different from first 2 cases.
}
To write down the if...else if...else steps for the above case, you will have to write the 'OR (||)' condition-statement and repeat the variable 'n' in the statement, Where as switch cases can be separated by just a comma ','. Thus switch is more readable for such a case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With