if else to switch statement

How to transform if-else statement to equivalent switch statement? I’m gonna show an example. Take a look at the following if-else statement :
function number(num){
	if(num < 0){
		alert("Number is negative");	
	}
	else if(num >= 0 && num <= 100){
		alert("Number is betwwen 0 and 100 (inclusive)");
	}
	else if(num > 100){
		alert("Number is greater than 100");
	}
	else{
		alert("This is not a number");
	}
}
First wrap the if-else inside switch block :
function number(num){
	switch(condition){//I'll tell the condition later
		if(num < 0){
			alert("Number is negative");	
		}
		else if(num >= 0 && num <= 100){
			alert("Number is betwwen 0 and 100 (inclusive)");
		}
		else if(num > 100){
			alert("Number is greater than 100");
		}
		else{
			alert("This is not a number");
		}
	}
}
if and all if-else blocks become our case blocks, and else will become default case :
function number(num
	switch(condition){//I'll condition later
		case (num < 0) : {
			alert("Number is negative");	
		}
		case (num >= 0 && num < 100) : {
			alert("Number is betwwen 0 and 100 (inclusive)");
		}
		case (num > 100) : {
			alert("Number is greater than 100");
		}
		default : {
			alert("This is not a number");
		}
	}
}
And don’t forget to add break :
function number(num
	switch(condition){//I'll condition later
		case (num < 0) : {
			alert("Number is negative");	
		}
		break;
		case (num >= 0 && num < 100) : {
			alert("Number is betwwen 0 and 100 (inclusive)");
		}
		break;
		case (num > 100) : {
			alert("Number is greater than 100");
		}
		break;
		default : {
			alert("This is not a number");
		}
	}
}
All cases are actually boolean (num < 0, num >= 0 && num < 100 and num > 100 are actually returning boolean). One of the case will eventually become true depending on the value of num. So our switch condition should be a boolean (true) so that it will match one of the cases :
function number(num
	switch(true){
		case (num < 0) : {
			alert("Number is negative");	
		}
		break;
		case (num >= 0 && num < 100) : {
			alert("Number is betwwen 0 and 100 (inclusive)");
		}
		break;
		case (num > 100) : {
			alert("Number is greater than 100");
		}
		break;
		default : {
			alert("This is not a number");
		}
	}
}
Done.

Leave a Reply

Your email address will not be published. Required fields are marked *