Switch case in a JavaScript function

Joined
Dec 1, 2022
Messages
1
Reaction score
1
Hi all!
I've used a switch case statement in a function that needs to determine the colour of a fruit. The issue is that I'm not sure how to get the outcome from the statement. Should I go for an if/else statement instead?
The code is as follows:
Code:
function fruitColor(fruit) {
    switch(color) {
        case "apple" : green;
            break;
        case "banana" : yellow;
            break;
        case "kiwi" : green;
            break;
        case "plum" : red;
            break;
    }
}

var result = fruitColor(plum);
I'm unable to obtain the result, and I'm not sure if I require a'return' value or something similar.
Before running this code, I did some web research and read a handful of articles to better comprehend the concept; my sources of information were Wiki, scaler, and GFG.
Thanks in advance!
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
Yes you need a return
Code:
case "banana" : return yellow; break;

In this case "break" is still needed even if a return statement is setted. Is green, yellow and red defined? Otherwise, if you wan't them to be strings, return this values in quotes.
 
Joined
Jul 12, 2020
Messages
89
Reaction score
9
JavaScript:
function fruitColor(fruit) {
    var color = 'unknown';
    switch(fruit) {
        case "apple" : color = 'green';  break;
        case "banana" : color = 'yellow';  break;
        case "kiwi" : color = 'green';  break;
        case "plum" : color = 'red'; break;
    }
    return color;
}

var result = fruitColor(plum);
The switch works off the value of the parameter being sent to the function.
 
Joined
Oct 21, 2022
Messages
2
Reaction score
0
Yes, you should use an if/else statement instead. The switch statement is used when you have to check for multiple conditions and then execute a block of code based on the result. In this case, you only have one condition (the fruit name) and then you want to return the corresponding color. An if/else statement would look something like this:
Code:
function fruitColor(fruit) {
    if (fruit == "apple") {
        return "green";
    }
    else if (fruit == "banana") {
        return "yellow";
    }
    else if (fruit == "kiwi") {
        return "green";
    }
    else if (fruit == "plum") {
        return "red";
    }
}

var result = fruitColor(plum);
console.log(result); // prints "red"
 
Joined
Nov 13, 2020
Messages
302
Reaction score
38
@Lauren431 you have taken a giant step backward in programming. The switch statement was introduced to replace the else if. It is cleaner code, easier to read, and executes faster than the elseIf . I can not think of one instance where you would want or need to choose an elseIf over a switch.
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
Does it look shorter?

JavaScript:
function fruitColor(fruit){
   const a = ['apple', 'banana', 'kiwi', 'plum'],
         b = ['green1', 'yellow', 'green2', 'red'];
   return b[a.indexOf(fruit)];
   }
  
   console.log( fruitColor('apple') );
   console.log( fruitColor('banana') );
   console.log( fruitColor('kiwi') );
   console.log( fruitColor('plum') );
 
Joined
Jul 12, 2020
Messages
89
Reaction score
9
if statements can be used for testing multiple conditions or conditional sets and still execute multiple functions if needed but do not always require and "else" statement.
JavaScript:
function fruitColor(fruit){
   if (fruit=='apple' || fruit=='kiwi'){ return "green"; }
   else if(fruit=='banana'){ return 'yellow'; }
   else if(fruit=='plum'){ return 'red'; }
   else { return 'unknown'; }
}

var result = fruitColor(plum);

And like BigDaddy said switch statements do create cleaner, easier to read coding when there's a lot of code to process by grouping it using a single value. But depending on the project, the switch condition can be set or changed by multple if statements that precede the switch. Picture it as a four-way stoplight. What actions would be taken in different instances.

JavaScript:
function fruitColor(fruit) {
    var color = 'unknown';
    switch(fruit) {
        case "apple" : color = 'green'; break;
        case "banana" : color = 'yellow';  break;
        case "kiwi" : color = 'green';  break;
        case "plum": color = 'red'; break;
    }
    return color;
}

var result = fruitColor(plum);

You learn all this as you begin learning how to simplify and reduce your code.
JavaScript:
function fruitColor(fruit){
  return (fruit=='apple'||fruit=='kiwi')?'green':(fruit=='banana')?'yellow':(fruit=='plum')?'red':'unknown';
}
 
Joined
Jul 12, 2020
Messages
89
Reaction score
9
using only if else and else if statements can become alot harder to read when a lil' more complexity is added to the mix...switches help you to break things down to simplified processes so you can see and learn more about patterns within the code...
JavaScript:
<html>
<head>
<title>Js Switches</title>
</head>
<body>
<script type="text/javascript">
/*-------------------------------------------------
Note the plural form of the friut must be entered
in order to return the correct response.
-------------------------------------------------*/
var fruit=[];
    fruit[0]='apples|green yellow red';
    fruit[1]='bananas|green greenish-yellow yellow';
    fruit[2]='kiwis|green';
    fruit[3]='plums|purple red';
    fruit[4]='grapes|green greenish-red greenish-purple purple';


var fruitnames='',fruitcolors='';
function getFruit(a){
   var fruits='',colors='';
   var response='Cannot search for information on an unknown friut or color!';

   function _process(process){
      for(var i=0; i<fruit.length; i++){
         var entry = fruit[i].split('|');
         switch(process){
            case 'setup':
               var ins = (i>0)? ' ':'';
               fruitnames  += ins+entry[0];
               fruitcolors += ins+entry[1];
            break;
            case 'name':
               if(entry[0] == a){colors = entry[1].split(' ').join(', ');break;}
            break;
            case 'color':
               if(entry[1].indexOf(a)!=-1){fruits += (i>0)? ', '+entry[0] : entry[0];}
            break;
         }//[ends switch]
      }//[end Loop]
      return;
   }

      //--- generate name & color selectors ---//
      if(fruitnames==''||fruitcolors==''){ _process('setup'); }

      //--- generate name based response ---//
      if(fruitnames.indexOf(a)!= -1){
         _process('name');
         response = 'Depending on how ripe they are, ' +a+ ', can be ' +colors+ '.'; }

      //--- generate color based response ---//
      else if(fruitcolors.indexOf(a)!= -1){
         _process('color');
         response = 'Friuts that are sometimes ' +a+ ' include ' +fruits; }

   document.write('<p>' +response+ '</p>');
}



getFruit();
getFruit('bananas');
getFruit('red');
getFruit('kiwis');
getFruit('purple');
</script>


</body>
</html>
Notice that there are three different processes that use the exact same loop...so the switched used in the embedded function changes whats generated according to which condition is met. responses are included in the conditional statements for easy modifications. Hope this helps.

Apologies for the late update, I lost the file hehehe.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top