最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Switch case in a JavaScript function - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Oct 25, 2020 at 20:02 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Mar 10, 2015 at 19:28 Thomas BengtssonThomas Bengtsson 3992 gold badges10 silver badges23 bronze badges 2
  • 1 You definitely need a return, at least one. Without a return no JavaScript function can return a value, which is what your last line expects. – Pointy Commented Mar 10, 2015 at 19:28
  • Yeah, return is needed in a function where you are setting a value by calling it. If you have a function that simply sets something or logs something, like console.log("Test") then a return isn't necessarily needed, but since you're trying to set result to the value of fruitColor(plum), you need to have the function spit something back at you. – Tim Lewis Commented Mar 10, 2015 at 19:35
Add a comment  | 

5 Answers 5

Reset to default 13

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

When coding, you always want to keep your code as high performance as possible. Now that I said that, let me give you some options to solve problems of this kind:

First, let’s go with your current solution and making it work.

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

var result = fruitColor(plum);

This one uses your switch construct and also returns prematurely, works.

However, it is not the best way to attack these kind of problems, because it generates code bifurcations that imply more memory is used to store and evaluate your code. Another way to do this is using an object with the fruits and colours.

function fruitColor(fruit) {
    var fruits = {
        apple  : 'green',
        banana : 'yellow',
        kiwi   : 'green',
        plum   : 'red'
    };
    return fruits[fruit] || 'not found';
}

var result = fruitColor('plum');

This code relies in a in-memory data base, works fast and has less bifurcations, but it also depends on a search.

This is my function implementation of the switch construct:

const fruitColor = fruit =>
  ({ apple: "green", banana: "yellow", kiwi: "green", plum: "red" }[fruit] ||
  "Nothing");

I would like to add a following up to Travis J's answer.

From here I want to emphasise how you can put your arguments into the switch statement. The parameter variables fruit and color takes an argument. If you want an argument taken from the function fruitColor into the switch statement, use the same parameter variable name. I.e., either use fruit for both, or color for both.

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":
            "green";
            return "green"; // Like this
            break;
        case "banana": "yellow"; // ^
            break;
        case "kiwi": "green"; // ^
            break;
        case "plum": "red"; // ^
            break;
    }
}
var result = fruitColor("plum");

First of all, in the switch statement, you have got to use the fruit argument, not the color and then you need a variable to store your choice:

function fruitColor(fruit) {
    switch(fruit) {
        case "apple" : result = green;
            break;
        case "banana" : result = yellow;
            break;
        case "kiwi" : result = green;
            break;
        case "plum" : result = red;
            break;
    }
    return result;
}

var result = fruitColor(plum);
发布评论

评论列表(0)

  1. 暂无评论