How to Change an If-Else Statement to a Switch Statement in JavaScript
In JavaScript, you can substitute the if...else statement with a switch statement.
The function below is an if-else statement:
function chainToSwitch(val){
let answer = "";
if (val === "hip hip") {
answer = "hooray!"
} else if (val === 7) {
answer = "Ate 9"
} else if (val === "Michael") {
answer = "Jackson"
} else {
answer = "Not this time!"
}
return answer;
}
The function below is a switch statement that achieves the same results:
function switchedChain(val){
let answer = "";
switch (val) {
case "hip hip":
answer = "hooray!";
break;
case 7:
answer = "Ate 9";
break;
case "Michael":
answer = "Jackson"
break;
default :
answer = "Not this time!"
break;
}
return answer;
}
The switch statement can simplify your code, making your life easier when writing JavaScript. Practice changing if-else statements to switch statements and let me know how it goes! You can find me on: Twitter, LinkedIn, or Github