If and Switch, the difference?

What is the difference between if and switch, like why, when and how should I use them in place of one another!

Regarding performance: it does not matter (it’s a super small micro optiomization).

Regarding code clarity: use if else statements if you have a small number of cases and use a switch statement if you have a big number of cases.

I would say it’s more that switch is for when you are checking different possible values of a single variable. if/else lends itself to more complex logic, but it can be less readable.

1 Like

I didn’t understand you that well, Sorry!
Would you please explain it properly

If you have a long list of specific values that a variable could be and your logic is fairly simple, then a switch is easier to read.

If your condition is more complex than seeing if the variable is equal to a value, then you need an if. Additionally, if the logic that you need to perform is complex, then an if/else is preferred.

1 Like

Thanks now I understood it.
Thanks for help!

I’m glad I could help. Happy coding!

1 Like