if there is a switch statement that has a default, would the same be achieved by just putting whatever is in the default under the switch statement?
1)
function test(foo) {
switch(foo.num) {
case "1":
return "hello"
case "2":
return "bye"
default:
return "neither"
}
}
function test(foo) {
switch(foo.num) {
case "1":
return "hello"
case "2":
return "bye"
}
return "neither"
}
do these both always operate the same way or is there something I am overlooking?
For what you're doing, they're the same, but only because you're returning. Switch is often used for other statements other than return though, eg:
function test(foo) {
switch(foo.num) {
case "1":
console.log('1');
break;
case "2":
console.log('2');
break;
default:
console.log('nope');
}
}
Above, it'll log exactly one value when the function is called. But if you do
function test(foo) {
switch(foo.num) {
case "1":
console.log('1');
break;
case "2":
console.log('2');
break;
}
console.log('nope');
}
it may log 1 or 2, but then it'll also log nope regardless - because you aren't returning inside the switch.
In the case that you just want to return a value depending on another value, consider using an object instead - it's a lot more concise (and easier to understand).
const returnValues = {
1: 'hello',
2: 'bye',
};
const test = foo => returnValues[foo] ?? 'neither';