I'm practicing Javascript and I wrote the following code by using the Switch Statement (it runs correctly):
function switchOfStuff(val) {
var answer = "";
switch (val) {
case 'a':
answer = 'apple';
break;
case 'b':
answer = 'bird';
break;
case 'c':
answer = 'cat';
break;
default:
answer = 'stuff';
}
return answer;
}
console.log(switchOfStuff('a'));
By substituting the Switch statement with a chaining if else statement I get the same output ("apple"
).
function switchOfStuff(val) {
if (val = 1) {
return "apple";
} else if (val = 2) {
return "bird";
} else if (val = 3) {
return "cat";
} else {
return "stuff";
}
return answer;
}
console.log(switchOfStuff('a'));
Both the snippets require 13/14 lines of code and return the same output: is there any reason why I should opt for the Switch Statement over the Chaining If Else Statement (or viceversa) and under what circumstances?