freeCodeCamp Challenge Guide: Adding a Default Option in Switch Statements

Adding a Default Option in Switch Statements


Hints

Hint 1

Adding a default option makes sure that in case your variable doesn’t match any of the options, the default will be used.


Solutions

Solution 1 (Click to Show/Hide)
function switchOfStuff(val) {
  var answer = "";

  switch (val) {
    case "a":
      answer = "apple";
      break;
    case "b":
      answer = "bird";
      break;
    case "c":
      answer = "cat";
      break;
    default:
      answer = "stuff";
  }

  return answer;
}
6 Likes

when others run across this -

make sure any alpha characters (a,b,c,d,…) used in your case are surrounded by " ".

even in the TEST -
switchOfStuff(“a,b,c,d,…”);

does not apply to NUMBERS

11 Likes

Here’s a complete working code.

function switchOfStuff(val) {
var answer = “”;
// Only change code below this line
switch (val){
case ‘a’:
answer = “apple”;
break;
case ‘b’:
answer = “bird”;
break;
case ‘c’:
answer = “cat”;
break;
default:
answer = “stuff”;
}

// Only change code above this line
return answer;
}

// Change this value to test
switchOfStuff(1);

13 Likes

Whats wrong with this switch statement? please help…

Looks like your code is a copy-paste??
why not follow the correct indentation for each line of codes.

Thank you, wasn’t sure why my code wasn’t working!

Actually, you didn’t add switch statement in your code.

1 Like

function switchOfStuff(val) {
var answer = “”;
// Only change code below this line

switch (val){
case ‘a’:
answer = “apple”;
break;
case ‘b’:
answer = “bird”;
break;
case ‘c’:
answer = “cat”;
break;
default:
answer = “stuff”;
}

// Only change code above this line
return answer;
}

// Change this value to test
switchOfStuff(a);

1 Like

My error occurs for defining a instead of ‘a’ in the following line:

switchOfStuff(‘a’);

3 Likes