Conditional statements
This chapter shows you how to write conditional branches (if and switch statements) in Office Scripts.
Branching with if statements
Section titled “Branching with if statements”Single condition
Section titled “Single condition”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).
const pi = 3.1415;
// If the condition is met, the code in {} runsif (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');Pi is greater than 3Pi is less than 4Multiple 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.
const root2 = 1.4142;
// First conditionif (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');}√2 is greater than 1Branching with switch statements
Section titled “Branching with switch statements”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.
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');}Tasty frozen or warmed upTasty as is or as juice