Sunday, May 19, 2024
71
rated 0 times [  76] [ 5]  / answers: 1 / hits: 20901  / 9 Years ago, tue, march 10, 2015, 12:00:00

I have a function that needs to pick out the color of a fruit and I have opted for a switch case statement. The problem is I'm not sure how to get the result out of the statement. Maybe I should get an if/else-statement instead?


Here is the 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 can't get the result and I'm not sure if I need a 'return' value or something like that.


More From » switch-statement

 Answers
22

The return statement ends function execution and specifies a value to be returned to the function caller. return MDN




There are a few missteps here aside from not returning a value. return is the facility to send a value back from a function, but in order for that to happen, no errors can occur. As it stands, the variable color is used in the switch statement, but it does not exist, perhaps because it was supposed to be fruit or vice versa. Further, the values in the resulting code for the case statements are basically just references to variables, and if there is no variable named green then it is just undefined. Perhaps you meant green.



function fruitColor(fruit) {
//note that there was no value color here, there was only the accepted
//parameter fruit, which should either be used or changed to color
switch(color) {
case apple :
//needs quotes, green with no quotes is a variable reference
green;
//note that simply using the string green doesn't accomplish anything though
//what we really need to do is send a value back, and in JavaScript you
//use the return keyword for that followed by the returning value
return green;//like this
break;
case banana : yellow;//^
break;
case kiwi : green;//^
break;
case plum : red;//^
break;
}
}
var result = fruitColor(plum);//needs quotes, plum would be a variable refernce


Personally, I prefer dictionaries for this type of work.



var fruitColors = {
apple : green,
banana : yellow,
kiwi : green,
plum : red
};
var plumColor = fruitColors[plum];//red

[#67496] Sunday, March 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aden

Total Points: 369
Total Questions: 100
Total Answers: 83

Location: Australia
Member since Tue, Oct 19, 2021
3 Years ago
;