Selecting from many options with Switch Statements - purpose of >>> var answer = “”; and >>>return answer;

I was doing the section “Selecting from many options with Switch Statements” and the instruction was not that clear. Eventually I resort to the getting a hint section and came to the forum that was now closed for further posts.

I got the answer but I still don’t understand the purpose of

var answer = “”; // at the beginning

and

return answer; // at the end

I deleted the beginning code >>> var answer ="";
and the switch function still works.

By the way, why is there no variable inside the double quotes? Does this mean that answer can be equal to anything? And why does the switch function still work without this statement?

However, the important code to include for this switch function is >>> return answer;
why do we need this statement here?

function caseInSwitch(val) {
  
  // Only change code below this line
 
  
  switch (val){
  
  case 1:
  answer = "alpha";
  break;
  
  case 2:
  answer = "beta";
  break; 

  case 3:
  answer = "gamma";
  break; 
      
  case 4:
  answer = "delta";
  break;
      
  default:   // optional, the switch function will work without the default
  answer = "statement you want to appear if val is not between 1-4";
  break;
  
  }
  
  // Only change code above this line  
 **return answer;**
  
}


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

Thank you very much for your help.

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

Noted and thank you for the edit.

var answer = ""; is declaring the variable answer and initializing it to an empty string. If you delete it entirely, then answer becomes a global variable. Review this challenge for details. You could declare it without initializing it and in this case that would be fine, but it’s often a good practice to initialize your variable to an empty string if you know that variable will contain a string.

This is what makes the function give us a result. If we don’t return answer, then our function didn’t actually do anything. We want to give caseInSwitch a value and get something back.

1 Like