Skip to content

Conditional statements

This chapter shows you how to write conditional branches (if and switch statements) in Office Scripts.

Write if () {} in that order. In (), write the condition (an expression that returns true or false), and in {}, write the code to run when the condition is met. Write the code to run when the condition isn’t met in else {} (optional).

Sample using an if statement
const pi = 3.1415;
// If the condition is met, the code in {} runs
if (pi > 3) {
console.log('Pi is greater than 3');
} else {
// Code to run when the condition isn't met
console.log('Pi is 3 or less');
}
// If the code after the branch is a single line, you can write it without {}
if (pi < 4) console.log('Pi is less than 4');
Output
Pi is greater than 3
Pi is less than 4

Multiple conditions (if…else if statements)

Section titled “Multiple conditions (if…else if statements)”

When there are two, three, or more conditions, you can add conditions with else if.

You can chain as many else if clauses as you like, but if any earlier condition is met, the code in that else if never runs.

Sample with multiple conditions
const root2 = 1.4142;
// First condition
if (root2 > 1) {
console.log('√2 is greater than 1');
// Second condition (doesn't run if the first one was met)
} else if (root2 > 1.1) {
console.log('√2 is greater than 1.1');
// When none of the conditions are met
} else {
console.log('√2 is 1 or less');
}
Output
√2 is greater than 1

When you use switch, you put the value to check in () and check whether it matches any of several case clauses. Values are compared using strict equality (===).

Code runs from the first matching case until it reaches break. If you don’t write break, the code for the next case also runs (in the sample below, the 'Orange' case has no break, so the second line is also output).

If none of the case clauses match, the code in default runs. If you omit default, nothing runs.

Sample using switch
const fruit: string = 'Orange';
switch (fruit) {
case 'Orange':
console.log('Tasty frozen or warmed up');
case 'Apple':
case 'Banana':
console.log('Tasty as is or as juice');
break;
default:
console.log('No recommended way to eat it was found');
}
Output
Tasty frozen or warmed up
Tasty as is or as juice