Search code examples
javascriptfunctionswitch-statementreturnconditional-statements

In a function with a declared empty variable, how does a switch statement automatically assign its return value to the empty variable?


all. I'm fairly new to JavaScript - currently trying to understand the switch statement. I'm having a problem understanding how I still got a return value when I did no assignments to my result variable. The switch statement is nested in a function.

function caseInSwitch(val) {
  let result = "";
  switch(val) {
    case 1:
      return "alpha";
      break;
    case 2:
      return "beta";
      break;
    case 3:
      return "gamma";
      break;
    case 4:
      return "delta";
      break;
  }

  return result;  
}

caseInSwitch(1);

I expect result to be an empty string "", but it shows the following value immediately... without any assignments...!


Solution

  • You're returning in the switch statement. In the case where val equals 1, the switch statement never gets past case 1. The function doesn't return result, it executes return "alpha".

    That return statement terminates the function:

    function caseInSwitch(val) {
      console.log("1: function start. Val:", val);
    
      let result = "";
      
      console.log("2: before switch");
      switch(val) {
        case 1:
          console.log("3: before return alpha");
          return "alpha";
          console.log("4: after return alpha");
          break;
        case 2:
          return "beta";
          break;
        case 3:
          return "gamma";
          break;
        case 4:
          return "delta";
          break;
      }
      console.log("5: after switch");
    
      return result;  
    }
    
    var finalResult = caseInSwitch(1);
    console.log("Final result:", finalResult);

    As you can see, only statements 1-3 get logged.

    The return statement in the switch also means the breaks are redundant:

    switch(val) {
        case 1:
            return "alpha";
        case 2:
            return "beta";
        case 3:
            return "gamma";
        case 4:
            return "delta";
    }
    

    Those break statements are only necessary to terminate the case, if you're not returning out of the case:

    let variable = "";
    switch(val) {
        case 1:
            variable = "alpha";
            break;
        case 2:
            variable = "beta";
            break;
        case 3:
            variable = "gamma";
            break;
        case 4:
            variable = "delta";
            break;
    }
    console.log(variable);