Default Option in case switch statements

Tell us what’s happening:

Can someone explain to me why is answer assigned to an empty string e.g. (var answer = “”)?
Seems redundant to me. Thanks.

Your code so far

function switchOfStuff(val) {
var answer = "";
// Only change code below this line
switch(val) {
  case "a":
  return "apple";
  case "b":
  return "bird";
  case "c":
  return "cat";
  return "stuff";

// Only change code above this line
return answer;

// Change this value to test

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Adding a Default Option in Switch Statements

Link to the challenge:

I think they expect you to assign a value to answer in your case statements rather than returning. ie,

case "a":
  answer = "apple";

rather than

case "a":
  return "apple";

It really doesn’t matter in the end.

By the way, if you use return inside a case then the break is unnecessary.

That makes sense now! and yeah good to know. Thanks fam

Hello Rosh.

Whilst it is not necessary to assign a variable anything, and you can just declare it:
let a;
In many languages, variable declaration is done by type. This way, the interpreter knows what to expect as a value, and if any other type is accidentally used on the variable, then a useful error is emitted. For example, in Java:

int a = 8;
String b = "Hello";

This is almost identical in many other languages. The reasons for doing this:

  1. Less chance of a silly coding mistake whereby you try to multiply a string with a number
  2. It can save memory, and, in languages without a compiler, it is incredibly useful and necessary.

JavaScript is similar, especially since the introduction of the const keyword. As, this now lets programmers have that little extra control over variables, which helps reduce simple mistakes.

If you are particularly interested, here is a lot more indepth information on the memory allocation

I hope this helps