Chapter 2 Read, repeat, branch ・ MISSION 9

Mission 9: Branch with if

📋 Mission list

Task

Write "Met" in the result column if sales are at or above the target, or "Missed" if they fall short. Exactly on target counts as "Met".

Sales results - Google Sheets
Sales results

For practice, the table goes back to its starting state every time before the code runs (a real spreadsheet doesn't go back. Script changes can sometimes be undone with Ctrl+Z, but not all at once).

Apps ScriptUntitled projectDeploy ▾
function judgeTargets() {
const sheet = SpreadsheetApp.getActiveSheet();
for (let row = 2; row <= sheet.getLastRow(); row++) {
const sales = sheet.getRange(row, 2).getValue();
const target = sheet.getRange(row, 3).getValue();
if (sales target) {
sheet.getRange(row, 4).setValue('Met');
} {
sheet.getRange(row, 4).setValue('Missed');
}
}
}
Ctrl+S: save · Ctrl+R: run (editor) · F5: reopen

Chapter 2 ・ MISSION 9

Branch with if

Write "Met" in the result column if sales are at or above the target, or "Missed" if they fall short. Exactly on target counts as "Met".

Now
Goal

Reading the code

if (sales >= target) {
If sales are at or above the target, run the { } right below.
sheet.getRange(row, 4).setValue('Met');
Writes "Met" in column D.
} else {
If the condition was not met, run this { } instead.

if (condition) { … } else { … } handles the case where the condition is met and the case where it isn't. The comparison operators are >= (at or above), > (greater than) and === (equal). Writing a single = puts in a value instead of comparing, so be careful.

How to get started with GAS and common code are covered in an article.What is GAS? Getting started and common code

The code you write runs in an isolated place inside this page. It can't reach outside the page or other sites.

* This is a simulation of how Google Sheets and Apps Script behave and may differ in some ways from the real thing.

* Google Sheets is a trademark of Google LLC. This site is not affiliated with Google.