settingsAccountsettings
Menusettings

Q: Fruit or Vegetable - JavaScript task

+2 votes

How to write a JS function to print "fruit", "vegetable" or "unknown" depending on the input string?

  • Fruits are: banana, apple, kiwi, cherry, lemon, grapes, peach
  • Vegetable are: tomato, cucumber, pepper, onion, garlic, parsley
  • All others are unknown

The input comes as a single string argument, the name of the fruit/vegetable/other thing:

Examples:

Input: banana

Output: fruit


Input: cucumber

Output: vegetable


Input: pizza

Output: unknown


The output should be printed to the console.

asked in JavaScript category by user richard8502

1 Answer

+1 vote

The fastest way to solve this javascript function is by using switch-case:

function checkFV(input) {
    switch (input) {
        case "banana":
        case "apple":
        case "kiwi":
        case "cherry":
        case "lemon":
        case "grapes":
        case "peach":
            console.log("fruit");
            break;
        case "tomato":
        case "cucumber":
        case "pepper":
        case "onion":
        case "garlic":
        case "parsley":
            console.log("vegetable");
            break;
        default:
            console.log("unknown");
            break;
    }
}

checkFV("pepper");

 

answered by user eiorgert
...