What is the difference between the if else statements & switch statement

What is the difference between the if-else statements & switch statement?
Wouldn’t it be better just to use a switch statement because the code is cleaner and render faster than an if-else statement?

Hey,
The first thing with switch statements is that it looks far neater and is easier to read. Probably the biggest difference is that switch statements despatches immediately to the case that is concerned usually by an index jump instead of having to go through all the conditions in an if else statement. Basically, switch is quicker. case values have some restrictions unfortunately. It can’t handle all datatypes which means that all the case values must be constant.

If/else statements check for equality as well as a logical expression (&& , || and !). Switch on the other hand only checks for equality. Unlike if/else, switch doesn’t decide which case is satisfied, rather which one to execute. I know this is really confusing, honestly it’s still a bit confusing to me so you might need to do some research to fully understand this.

Here’s a page that explains it in more detail: https://techdifferences.com/difference-between-if-else-and-switch.html

1 Like