Conditional logic in Apps Script
Conditional logic is used to make your program do something only if a condition is met.
IF statement
The IF statement will first check if a condition that you specify is met. If the condition is met, the code within curly braces ({ and }) will be executed. If the condition is not met, the code within the curly braces will NOT be executed.
The code within the curly braces is called the IF block. This is the code block that will get executed if the condition is met.
The condition to be checked must be an expression that evaluates to some value. If it evaluates to TRUE, the condition is deemed to be met.
if (some condition is met) {
//do something
}
Here is an example:
if (testScore >= 40 ) {
//student passed the test
return true;
}
Type conversion
The condition to be checked must evaluate to a value. However, this value does not have to be a boolean. Apps Script will convert the value to a boolean before checking to see if it is true.
For example, consider the following code.
if (10) {
//do something
}
The code within the curly braces will be executed since Apps Script will convert the value 10 to true.
The rules that govern conversion to boolean are as follows
The number 0 and an empty string ("") are converted to false.
The values null, NaN and undefined are converted to false.
All other values are converted to true.
A note on null and NaN
A null value is similar to undefined. It represents something that does not exist.
NaN stands for "not a number". This value is usually the result of Apps Script encountering something else when it is expecting a number. For example, trying to divide a number by a string will result in NaN.
Logger.log(3 / "this is a string"); //outputs NaN
IF - ELSE statement
The IF - ELSE statement has two blocks of code. The IF block and the ELSE block. The IF block is executed if the condition is met. The ELSE block is executed if the condition is NOT met.
if (some condition is met) {
//IF block
//do something
} else {
//ELSE block
//do something else
}
Here is an example:
if (testScore >= 40 ) {
//student passed the test
return true;
} else {
//student failed the test
return false;
}
IF - ELSE - IF ladder
The IF - ELSE ladder can be used to chain together a series of conditional statements. Let's say you want to assign grades based on test scores. The grading key is as follows:
A: score >= 85
B: score >= 70 and score < 85
C: score >= 55 and score < 70
D: score >= 40 and score < 55
F: score < 40
Here is how you might implement a function that accepts the test score as input and outputs the grade.
function scoreToGrade(score) {
if (score >= 85) {
return "A";
} else if (score >= 70) {
return "B";
} else if (score >= 55) {
return "C";
} else if (score >= 40) {
return "D";
} else {
return "F";
}
}
The above function first checks if the score is greater than or equal to 85. If yes, it returns "A". If not, it checks if the score is greater than or equal to 70. If yes, it returns "B". If not, it checks if the score is greater than or equal to 55. If yes, it returns "C". If not, it checks if the score is greater than or equal to 40. If yes, it returns "D". If not, there is nothing left to check, it returns "F".
Switch Statements
A switch statement provides a cleaner way to handle multiple conditions compared to long if-else chains. It evaluates an expression and executes code based on matching cases.
switch (expression) {
case value1:
// Code to execute
break;
case value2:
// Code to execute
break;
default:
// Default code
}
Switch vs If-Else: When to Use Each
The traditional if-else chain checks each condition one after another. While this works, it can become harder to read as more conditions are added:
// Using if-else chain
function getGradeMessage(grade) {
if (grade === 'A') {
return "Excellent!";
} else if (grade === 'B') {
return "Good job!";
} else if (grade === 'C') {
return "Passed";
} else {
return "Need improvement";
}
}
Switch statements offer a cleaner, more organized way to handle multiple conditions. The code layout makes it easier to scan and understand at a glance:
// Using switch statement
function getGradeMessage(grade) {
switch (grade) {
case 'A':
return "Excellent!";
case 'B':
return "Good job!";
case 'C':
return "Passed";
default:
return "Need improvement";
}
}
Key Features1. The Break Statement
The break statement is crucial in switch statements. Without it, code execution will continue into the next case, which can lead to unexpected results. Think of it like putting up a wall between cases - once hit, you exit the switch block entirely:
switch (dayNum) {
case 1:
Logger.log("Monday");
break; // Exit the switch
case 2:
Logger.log("Tuesday");
break;
// ... more cases
}
In the above code, when dayNum
is 1, it logs "Monday" and then encounters the break statement, immediately exiting the switch block. Without the break statement, it would continue executing the next case and log "Tuesday" as well, which isn't what we want.
2. Fall-Through Cases
Sometimes you want multiple cases to execute the same code. By omitting the break statement between cases, you can create a "fall-through" effect. This is particularly useful when several cases should trigger the same behavior:
switch (dayNum) {
case 1:
case 2:
case 3:
case 4:
case 5:
Logger.log("Weekday");
break;
case 6:
case 7:
Logger.log("Weekend");
break;
}
In this example, any value of dayNum
from 1 through 5 will "fall through" to the Logger.log("Weekday")
statement. There's no break statement between these cases, so they all execute the same code. Similarly, values 6 and 7 both execute the weekend code. This is much cleaner than writing five separate cases that all do the same thing.
3. Default Case
The default case acts as a catch-all for any value that doesn't match your defined cases. It's like an else statement in an if-else chain. Always include a default case to handle unexpected inputs and make your code more robust:
switch (status) {
case 'active':
processActive();
break;
case 'pending':
processPending();
break;
default:
handleUnknownStatus(); // Catches all other values
}
In this code, if status
is neither 'active' nor 'pending', the default case executes handleUnknownStatus()
. This ensures your code has a way to handle unexpected values gracefully instead of failing silently. For example, if status
is 'cancelled' or has a typo like 'aktive', the default case will catch it.
Best PracticesAlways include a break
statement (unless fall-through is intended)
Use a default
case to handle unexpected values
Consider readability when choosing between switch and if-else
Quick Reference Table
Always include a break
statement (unless fall-through is intended)
Use a default
case to handle unexpected values
Consider readability when choosing between switch and if-else
Feature | Description | Use Case |
---|---|---|
break | Exits the switch block | Prevent fall-through |
fall-through | Multiple cases sharing code | Group related cases |
default | Handles non-matching values | Error handling |
case values | Must be constants | Match specific conditions |