Disclaimer: I am learning in public so please do correct me if I get something wrong
I am going to explain both using the same example. The example will be in Ruby since that's the language I'm learning.
We want to define a statement that returns what someone should wear under different temperatures (in Celsius):
An if statement will look something like this:
if weather > 30 puts "Heat wave, stay indoor" elsif weather (<= 30 && > 20) puts "shorts, T-shirt, sunglasses" elsif weather (<= 20 && > 10) puts "jumper and long trousers" else puts "wear a thick jacket" end
Whereas a switch statement in Ruby looks like this:
case weather when > 30 puts "Heat wave, stay indoor" when 21..30 puts "shorts, T-shirt, sunglasses" when 11..20 puts "jumper and long trousers" else puts "wear a thick jacket end
In an if statement, anything can be the condition, it doesn't necessarily have to be the weather like we've defined above, for example, we can take an extra argument like this:
if weather > 30 puts "Heat wave, stay indoor" if weather > 30 && work_from_home == false puts "short sleeve and loads of sunscreen" elsif weather (<= 30 && > 20) puts "shorts, T-shirt, sunglasses" elsif weather (<= 20 && > 10) puts "jumper and long trousers" else puts "wear a thick jacket" end
here we added an additional argument called work_from_home that gives a true or false output if we are working from home or not. An if statement can handle configurations like this.
However, a switch statement takes the output of the case argument and see which switch condition it satisfies. So it is very useful if all the conditions are only dependent on one variable. In some cases, writing a switch statement can make your code cleaner if you have only one variable your statement depends on.
I hope you find this useful. Have a nice day!