I couldn't find any documentation or questions about whether it's possible to write the case
statements in a switch statement on one line nor what the best practice and way to write them on one line in JavaScript is.
The most related questions were: CodeGrepper Question and Switch statement for multiple cases in JavaScript
I currently have a function with a switch statement that returns a product's name:
function returnProduct(product) {
switch (product) {
case 'aa': case 'AApple':
return 'AApple';
case 'bb': case 'BananaBall':
return 'BananaBall';
case 'ee': case 'ElephantElf':
return 'ElephantElf';
default:
return 'Sorry we don\'t have that yet';
}
}
console.log(returnProduct('aa'));
console.log(returnProduct('error'));
console.log(returnProduct('ee'));
console.log(returnProduct('BananaBall'));
CodePudding user response:
Solution
function returnProduct(product) {
switch (product) {
case 'aa': case 'AApple': { return 'AApple'; }
case 'bb': case 'BananaBall': { return 'BananaBall'; }
case 'ee': case 'ElephantElf': { return 'ElephantElf'; }
default: {return 'Sorry we don\'t have that yet'; }
}
}
console.log(returnProduct('aa'));
console.log(returnProduct('error'));
console.log(returnProduct('ee'));
console.log(returnProduct('BananaBall'));
This was my first proposed solution which solves my problem but I hadn't tested it enough and had some errors which the community helped me fix.
If there is a better answer or better way of doing this please let me know.
If not I hope that others asking the same question will be able to find this solution.
CodePudding user response:
Seems you have missed break statement.
Or Try using **dictionary**
var x ='aa':'AApple','AApple':'AApple','bb':'BananaBall',
'BananaBall':'BananaBall'};
var key='aa';
var z;
if(x[key] !== undefined)
return x[key];