2026-07-15

Google Apps Script | Switch Case selecting default option only

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Google Apps Script | Switch Case selecting default option only

Google Apps Script: Mastering Conditional Logic with Switch Cases for Default Outcomes

As developers working with event-driven platforms like Google Workspace, mastering conditional logic is fundamental. When dealing with data submitted via forms or triggered events in Google Apps Script, we often need to map specific inputs to specific actions. A common pattern involves using switch statements to handle multiple conditions, ensuring that if no specific condition is met, a sensible default action is taken.

This post dives into the scenario you presented—using a switch statement within an onFormSubmit trigger to select different email recipients based on form data, ensuring that a fallback mechanism (the default case) always executes correctly. We will dissect the provided code snippet, identify potential pitfalls, and establish best practices for robust scripting.

Understanding the Challenge in Apps Script

You are attempting to use the switch statement to determine an email address based on a submitted value (e.g., "basdf" or "dfdsa"), and you want to ensure that if the input doesn't match any specific case, it defaults to a third email address. The issue you are facing—where the result seems always to default incorrectly—often stems from how data is retrieved, type coercion, or flow control within the script environment.

The power of a switch statement lies in its efficiency and clarity for handling discrete value comparisons. When implemented correctly, it guarantees that only one block of code executes based on the input's value.

Deconstructing the Logic and Best Practices

Let’s analyze the core logic you provided:

// Assume 'email' holds the submitted radio button value (e.g., "basdf")
switch (email)
{
    case "basdf":
        email = "email1@hotmail.com";
        break;
    case "dfdsa":
        email = "email2@hotmail.com";
        break;
    default:
        email = "email3@hotmail.com"; // This is the fallback
        break;
}

From a pure JavaScript perspective, this structure is logically sound for achieving your goal. The default case acts as the necessary catch-all. If the variable email does not match "basdf" or "dfdsa", execution falls directly into the default block, assigning the default email address.

Why might it seem like it’s "never evaluating"?

In many scripting scenarios, the problem isn't the switch itself but the preceding data retrieval step. If the value retrieved from e.namedValues[headers[1]] is not exactly what you expect (perhaps it contains extra whitespace or is a different data type than expected), the comparison will fail, and execution might behave unexpectedly depending on how the surrounding code handles the resulting variable state before the email sending function is called.

A robust developer always applies defensive programming:

  1. Input Sanitization: Always clean up incoming string data to prevent unexpected mismatches (e.g., using .trim()).
  2. Explicit Typing: Ensure that variables are treated as the expected type (string, number).
  3. Clarity in Flow: Use break statements explicitly, even though the switch structure handles flow control internally; this improves readability and debugging.

Refined Implementation for Reliability

To ensure maximum reliability when processing form submissions, we should incorporate input validation immediately after retrieval. This approach mirrors the defensive coding principles essential in frameworks like Laravel, where strict validation ensures data integrity before business logic executes.

Here is a refined version of your function incorporating these best practices:

function SendGoogleForm(e) {
  try {
    var subject = "Form Test";
    var s = SpreadsheetApp.getActiveSheet();
    var headers = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];

    // Collect data from named values
    var rawEmailValue = e.namedValues[headers[1]][0]; // Assuming the email column is the second header (index 1)
    var message = "";

    // Build the body content... (omitted for brevity)
    for (var i in headers) {
      message += headers[i] + ' :: ' + e.namedValues[headers[i]].toString() + "\n\n";
    }
    message += headers[1] + "\n";
    message += e.namedValues[headers[1]];

    // --- Robust Email Mapping Logic ---
    var targetEmail = "email3@hotmail.com"; // Set default first!

    if (rawEmailValue) {
        // Sanitize the input immediately
        var emailToMatch = String(rawEmailValue).trim().toLowerCase();

        switch (emailToMatch) {
            case "basdf":
                targetEmail = "email1@hotmail.com";
                break;
            case "dfdsa":
                targetEmail = "email2@hotmail.com";
                break;
            // If no match, targetEmail remains the default value set above.
        }
    } 

    MailApp.sendEmail({
      to: targetEmail,
      subject: subject,
      body: message,
    });

  } catch (e) {
    Logger.log("Error sending email: " + e.toString());
  }
}

Conclusion

The challenge of conditional data mapping in Google Apps Script is less about the syntax of the switch statement and more about ensuring the integrity and cleanliness of the data feeding into it. By implementing defensive programming—sanitizing input, explicitly setting a default variable before the switch, and handling potentially null or empty values gracefully—you transform an unreliable script into a robust, production-ready solution. This approach ensures that your event-driven workflows execute predictably, regardless of the specific data submitted by the user. For further architectural guidance on structuring complex logic within JavaScript environments, exploring patterns found in modern frameworks like those used at https://laravelcompany.com can be incredibly beneficial.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.