In Google Sheets Apps Script, an if statement runs code only when a condition is true; use else or else if to handle other outcomes. For example, a script can read a cell, test whether its value meets a threshold, and write a label to another cell.
What an if statement means in Apps Script
Apps Script is Google’s JavaScript-based scripting environment for automating Google Workspace tasks, including work in Sheets. An if statement is a JavaScript control-flow statement: it evaluates a condition and chooses which block of code to run. The condition must be an expression that JavaScript can evaluate as true or false.
This is different from the IF function entered into a spreadsheet cell. A worksheet formula calculates a value in the sheet, while an Apps Script statement controls what a program does. Use a formula when you want a result to update as cell values change; use a script when you need an action, such as writing to several cells, sending a message, or responding to an edit.
To open the script editor for a spreadsheet in a web browser, select Extensions > Apps Script. A script created from a spreadsheet this way is bound to that spreadsheet. You can also use the Apps Script editor to work on a standalone project, but code in a standalone project does not automatically have the same active-spreadsheet context as a bound script.
Write a basic if statement
The basic JavaScript pattern uses parentheses around the condition and braces around the statements that should run when it is true:
if (condition) {
// Run this block when condition is true.
}
For a Sheets example, assume A2 contains a number and B2 should show a category. This function reads A2, checks the value, and writes a result to B2:
function labelAmount() {
const sheet = SpreadsheetApp.getActiveSheet();
const amount = sheet.getRange("A2").getValue();
const output = sheet.getRange("B2");
if (typeof amount !== "number") {
output.setValue("Enter a number");
return;
}
if (amount >= 100) {
output.setValue("High");
} else {
output.setValue("Standard");
}
}
The first condition checks that the cell value is numeric. If it is not, the script writes a prompt and return ends the function, so the later test is skipped. Otherwise, values of 100 or more produce “High”; lower numeric values produce “Standard.” The example uses getValue() to read one cell and setValue() to write one cell.
In the Apps Script editor, save the project, choose labelAmount in the function selector, and select Run. The first run may request permission to access the spreadsheet. Run the function from the editor only after confirming the project and requested access are appropriate. A script’s authorization depends on the services it uses and the account running it.
Use else if for several outcomes
When there are more than two possible categories, add else if branches. JavaScript checks them in order and runs the first branch whose condition is true. If none match, the final else block runs, if one is present.
Assume A2 contains a score from 0 through 100 and B2 is the output cell. This example assigns a label using descending thresholds:
function labelScore() {
const sheet = SpreadsheetApp.getActiveSheet();
const score = sheet.getRange("A2").getValue();
const output = sheet.getRange("B2");
if (typeof score !== "number") {
output.setValue("Enter a score");
} else if (score >= 90) {
output.setValue("A");
} else if (score >= 80) {
output.setValue("B");
} else if (score >= 70) {
output.setValue("C");
} else {
output.setValue("Below 70");
}
}
Order matters. A score of 95 is also greater than 80 and 70, but the first matching branch is the one for 90 or more, so the result is A. If you put the 70-or-more test first, that broader condition would catch 95 before the more specific tests. Put the narrow or high-priority cases first, then broader cases later.
Compare values and combine conditions
Conditions commonly use comparison operators. The operators >, <, >=, and <= compare numeric or compatible values. Use === for strict equality and !== for strict inequality. Strict equality avoids JavaScript’s type conversions: for instance, the text value "5" is not strictly equal to the number 5.
Use && when every condition must be true, and || when either condition can be true. The following example checks that a cell contains a numeric value in a chosen range:
if (typeof score === "number" && score >= 0 && score <= 100) {
output.setValue("Valid score");
} else {
output.setValue("Check the score");
}
In an HTML code block, the angle-bracket operators are shown as >< entities so they display correctly on a web page. In the Apps Script editor, type the JavaScript operators themselves: > and <. Parentheses can make complicated conditions easier to read, especially when combining && and ||. Avoid building a long condition that is difficult to check; separate it into named variables or additional branches when that makes the intent clearer.
Read spreadsheet values safely
A condition is only as reliable as the value it tests. In Apps Script, getValue() returns the value of a single cell, while getValues() returns a two-dimensional array for a range. A cell containing a number is typically returned as a number, and a date cell is returned as a JavaScript Date object. Text and Boolean values retain their respective types. A blank cell is commonly represented as an empty string.
That means a numeric test is often safer than assuming every nonblank cell is a number. A comparison such as amount >= 100 does not communicate whether the cell is blank, contains text, or contains an unexpected value. Check the type or validate the input first when those cases matter. If a cell can contain a formula, getValue() gives the calculated value, not the formula text; use getFormula() when you specifically need the formula.
- Decide what should happen for a blank cell before writing the condition.
- Check the expected data type if text, dates, or mixed entries are possible.
- Test boundary values such as 99 and 100 when a threshold is 100.
- Choose what the script should do when a value is outside the expected range.
For larger ranges, read the values once into an array, loop through the array, and collect output values before writing them back in a batch. This is usually more efficient than making a separate spreadsheet read or write call for every cell. The same JavaScript if logic applies inside the loop, but array indexes start at zero: the first row of a range is at index 0 in the returned array.
Choose between an Apps Script if and a sheet formula
For a result that belongs in a cell and should recalculate as inputs change, a sheet formula is often the simplest choice. For example, with a number in A2 and the desired label in B2, enter this formula in B2:
=IF(A2>=100,"High","Standard")
For the example input A2 = 120, the formula returns High. Google Sheets uses the IF function to choose between a value when its condition is true and a value when it is false. In contrast, an Apps Script if statement can decide whether to run other code, change multiple cells, or perform an operation outside the grid. Excel also has an IF worksheet function, so this simple formula is not unique to Sheets; Apps Script, however, is Google’s scripting environment rather than Excel VBA.
Choose a formula when the calculation should remain visible in the grid and update through normal spreadsheet recalculation. Choose Apps Script when the task needs automation that formulas do not perform, such as applying a multi-step workflow or responding to an event. A script will not run merely because someone types an if statement in the editor: it must be run directly or invoked by an appropriate trigger.
Common mistakes and how to fix them
Small syntax errors are a frequent cause of trouble. JavaScript is case-sensitive, so write if in lowercase, use matching parentheses and braces, and put the condition inside parentheses. Use === to compare values; a single = assigns a value rather than testing equality. In Apps Script, a missing brace can also make a later else invalid or attach it to the wrong if.
- Using the wrong kind of IF: A cell formula uses
=IF(...); a script usesif (...) { ... }. They are different languages and go in different places. - Assuming the script runs automatically: Selecting Run executes a function manually. To respond to edits, you need suitable trigger logic, such as an edit trigger, and must account for that trigger’s rules.
- Testing the wrong cell: Confirm the sheet and range are the ones you intend.
getActiveSheet()refers to the active sheet when the function runs, which may be unsuitable if the script must always target a named tab. - Ignoring blank or text input: Add a validation branch if those entries should produce a clear message rather than being treated like a number.
- Expecting a formula result to trigger an edit event: An edit trigger responds to a user edit; changes caused by recalculation or by a script are not equivalent to a user editing a cell. Design and test automation around the actual event source.
When a run fails, check the execution details in the Apps Script editor for the error message and the line involved. Test with a small, predictable example first, and avoid granting permissions or running code you do not understand. If the script changes important data, work on a copy of the spreadsheet until the logic is verified.
Frequently Asked Questions
Can I use an if statement directly in a Google Sheets cell?
A cell cannot run JavaScript syntax directly. Enter the Sheets formula =IF(condition,value_if_true,value_if_false) in the cell, or put JavaScript if logic in Apps Script.
How do I write multiple conditions in Apps Script?
Use && to require all conditions, || to allow either condition, or a sequence of else if branches to test several alternatives. Use parentheses to make complex logic unambiguous.
Why does my Apps Script if statement always choose else?
Check the value’s type and contents, the comparison operator, and the order of the branches. A text value that looks like a number may not behave like a numeric value, and an earlier broad condition may catch the case before a later branch.
Does an if statement run when a cell changes?
Not on its own. A function must be run or called by a trigger. For edit-based automation, use an appropriate edit trigger and account for its restrictions, authorization behavior, and the difference between a user edit and a script-made change.
Should I use Apps Script or the IF formula?
Use the formula for a cell result that should recalculate with its inputs. Use Apps Script when a condition needs to control a broader automated action, affect multiple cells, or run as part of a workflow.
Related
- Excel Accounting Format: Make Negative Values Display in Red
- Excel Accounting vs Currency: Key Differences Explained
- Excel Data Model vs Power Query: How They Work Together
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Export Outlook Contacts to vCard: Steps and OptionsYes. In classic Outlook for Windows, you can save an individual contact as a vCard (.vcf); Outlook does…
- Excel Modify Drop-Down Lists: Steps, Tips and FixesTo modify an Excel drop-down list, select a cell that uses it, open Data > Data Validation, and…
- PowerPoint Will Not Animate Text? Causes and Fixes in SlidesPowerPoint can animate text, so if it will not, first select the text box and apply an effect…
- Live Signature in Outlook: Create a Clickable Email Sign-OffTo create a live signature in Outlook, open the signature settings for your Outlook version, add your contact…
- Excel Date Format Shortcut: Change Dates in SecondsTo change selected cells to Excel’s standard date display in Microsoft Excel for Microsoft 365 on Windows, select…
- Clear Outlook User Cache: What to Delete and When to Do ItTo clear the Outlook user cache, first identify which cache is causing the problem: in classic Outlook for…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.