Skip to main content

Conditional formula

In this chapter, you can understand how to write conditional expressions (if sentences) using office scripts.

Conditional branch using ## if statement

In the case of a single condition

Write in the order of if () {}, describe the condition formula (type that returns true or false) in (), and {}.

Sample using if statement
const pi = 3.1415;

// If the conditions match, the processing in {} is executed
if (pi > 3) {
console.log('The pi is larger than 3');
} else {
// Processing if it does not match the conditions
console.log('The pi is 3 or less');
}

// If the processing after the branch is one line, it can be described without attaching {}.
if (pi < 4) console.log('The pi is less than 4');
Execution result
The pi is larger than 3
The pi is less than 4
tip

If the processing that matches the condition is completed in one line, {} can be omitted, but it is recommended that {} be described in consideration of readability and expandability.

In the case of multiple conditions (if ... else if statement)

If there are two or three conditions, you can set the conditional formula using else if.

else if can be connected as many as possible, but if it matches any of the previous if sentences, the process will not be executed.

Sample of multiple conditions
const root2 = 1.1415;

// First condition
if (root2 > 1) {
console.log('√2 is larger than 1');

// Second condition (if it matches the first, it will not be executed)
} else if (root2 > 1.1) {
console.log('√2 is larger than 1.1');

// If it does not match any of the conditions
} else {
console.log('√2 is 1 or less');
}
Execution result
√2 is larger than 1

Switch Conditional branch

If you use switch, you can set the value to be verified in () and verify that it matches multiple case.

The processing is executed from the first match case to break.

If not all case match, the processing in default will be executed.If omitted, the process will not be executed.

Sample using switch statement
const fruit: string = 'Orange';

switch (fruit) {
case 'Orange':
console.log('It is delicious even if you freeze or warm');

case 'Apple':
case 'Banana':
console.log('It is delicious as it is or juice');
break;

default:
console.log('I couldnt find a recommended way to eat');
}
Execution result
It is delicious even if you freeze or warm
It is delicious as it is or juice