Skip to content

Apps Script tips and tricks

125 Apps Script tips, with before-and-after code.

125 practical Google Apps Script tips and tricks with before-and-after code, covering triggers, Sheets ranges, performance, services, HTML Service, and manifests.

Built from the language server

Every tip maps to a live editor check.

Each tip on this page comes from a rule in myFunction's Apps Script language server. Every before-and-after example runs through the test suite, which checks that the language server flags the first snippet and stays quiet on the second.

The Chrome extension checks all 125 patterns as you type at script.google.com and offers quick fixes or written guidance for 69 of them. Looking for rule codes, severity levels, and MCP or VS Code support instead? Read the diagnostic coverage reference.

21 tips

Triggers, web apps, and add-ons

Avoid silent trigger misses, web app response errors, and add-on auth traps.

Tip 001 Avoids silent bug MF93001

Match exact camelCase for onOpen, onEdit, doGet, and doPost

Apps Script calls onOpen, onEdit, onSelectionChange, onInstall, doGet, and doPost by exact name. A function named onedit or DoGet never runs.

In myFunction: Rename the function to the exact trigger name.

Avoid 1 changed line
function onedit(e) {
  e.range.setNote("Edited");
}
Prefer 1 changed line
function onEdit(e) {
  e.range.setNote("Edited");
}
Tip 002 Avoids silent bug MF93002

Use an installable trigger when a handler needs authorization

onOpen, onEdit, and onSelectionChange run without authorization. Calls to GmailApp, MailApp, UrlFetchApp, DriveApp, CalendarApp, or ContactsApp, or opening another file by ID or URL, fail when the trigger fires.

Avoid 1 changed line
function onEdit(e) {
  MailApp.sendEmail("team@example.com", "Sheet edited", e.range.getA1Notation());
}
Prefer 2 changed lines
// Run from an installable "On edit" trigger.
function notifyOnEdit(e) {
  MailApp.sendEmail("team@example.com", "Sheet edited", e.range.getA1Notation());
}
Tip 003 Avoids silent bug MF93003

Always return an HtmlOutput or TextOutput from doGet and doPost

A web app must return an HtmlOutput or TextOutput. Without a return value, visitors see "The script completed but did not return anything."

In myFunction: Return the HtmlOutput or TextOutput the last line builds, evaluating a template first.

Avoid 1 changed line
function doGet(e) {
  HtmlService.createHtmlOutput("<p>Hello</p>");
}
Prefer 1 changed line
function doGet(e) {
  return HtmlService.createHtmlOutput("<p>Hello</p>");
}
Tip 004 Prevents runtime error MF93004

Point menus, triggers, and add-ons at existing public functions

Menu.addItem(), ScriptApp.newTrigger(), CardService.Action.setFunctionName(), and addOns trigger fields in appsscript.json take the function name as text, and Apps Script only looks it up when the item is clicked or the trigger fires. A misspelled name, one written with parentheses, or a private function ending in _ for a CardService or add-on callback fails with "Script function not found". When the whole project is loaded, any missing function name is reported; otherwise only close matches, parentheses, and private add-on callbacks are flagged.

In myFunction: Change the name to the matching function, or drop the parentheses.

Avoid 1 changed line
function onOpen() {
  SpreadsheetApp.getUi().createMenu("Reports").addItem("Build", "buildReprot").addToUi();
}

function buildReport() {}
Prefer 1 changed line
function onOpen() {
  SpreadsheetApp.getUi().createMenu("Reports").addItem("Build", "buildReport").addToUi();
}

function buildReport() {}
Tip 005 Prevents runtime error MF93005

Pass 1, 5, 10, 15, or 30 to ClockTriggerBuilder.everyMinutes()

ClockTriggerBuilder.everyMinutes() accepts only 1, 5, 10, 15, or 30. Any other number makes the trigger setup fail.

In myFunction: Use the nearest supported interval.

Avoid 1 changed line
function installTrigger() {
  ScriptApp.newTrigger("syncRows").timeBased().everyMinutes(2).create();
}
Prefer 1 changed line
function installTrigger() {
  ScriptApp.newTrigger("syncRows").timeBased().everyMinutes(5).create();
}
Tip 006 Prevents runtime error MF93006

Call .evaluate() before returning an HtmlTemplate from a web app

createTemplateFromFile() returns an HtmlTemplate. A web app needs the HtmlOutput that evaluate() produces, so returning the template itself fails.

In myFunction: Append .evaluate().

Avoid 1 changed line
function doGet(e) {
  return HtmlService.createTemplateFromFile("Index");
}
Prefer 1 changed line
function doGet(e) {
  return HtmlService.createTemplateFromFile("Index").evaluate();
}
Tip 007 Best practice MF93007

Set ContentService.MimeType.JSON when serving JSON from a web app

ContentService.createTextOutput() serves plain text unless setMimeType() says otherwise, so a JSON response arrives as text/plain.

In myFunction: Append .setMimeType(ContentService.MimeType.JSON).

Avoid 1 changed line
function doGet(e) {
  return ContentService.createTextOutput(JSON.stringify({ ok: true }));
}
Prefer 1 changed line
function doGet(e) {
  return ContentService.createTextOutput(JSON.stringify({ ok: true })).setMimeType(ContentService.MimeType.JSON);
}
Tip 008 Avoids silent bug MF93008

Do not attach an installable trigger to a simple trigger name

A function named onOpen, onEdit, onSelectionChange, or onInstall already runs as a simple trigger. An installable trigger that points at it makes the function run from both triggers, for example twice on every edit.

Avoid 2 changed lines
function installEditTrigger() {
  ScriptApp.newTrigger("onEdit").forSpreadsheet(SpreadsheetApp.getActive()).onEdit().create();
}

function onEdit(e) {
  e.range.setNote("Edited");
}
Prefer 2 changed lines
function installEditTrigger() {
  ScriptApp.newTrigger("onEditInstalled").forSpreadsheet(SpreadsheetApp.getActive()).onEdit().create();
}

function onEditInstalled(e) {
  e.range.setNote("Edited");
}
Tip 009 Best practice MF93009

Call onOpen(e) inside onInstall(e) so add-on menus appear right away

When a user installs an editor add-on, only onInstall() runs, so the add-on menu stays missing until the file is reopened. Google's add-on samples call onOpen(e) from onInstall(e).

In myFunction: Add onOpen(e) as the first line of onInstall().

Avoid 1 changed line
function onOpen(e) {
  SpreadsheetApp.getUi().createAddonMenu().addItem("Run report", "runReport").addToUi();
}

function onInstall(e) {
  Logger.log("Installed");
}

function runReport() {}
Prefer 1 changed line
function onOpen(e) {
  SpreadsheetApp.getUi().createAddonMenu().addItem("Run report", "runReport").addToUi();
}

function onInstall(e) {
  onOpen(e);
}

function runReport() {}
Tip 010 Avoids silent bug MF93010

Keep getUi() and Browser dialogs out of web apps and background triggers

getUi() and Browser dialogs need an open Sheets, Docs, Slides, or Forms editor. When doGet, doPost, a time-driven trigger, or a form-submit trigger reaches them, directly or through other functions, the call throws. Calls inside a try block are skipped.

Avoid 1 changed line
function doGet() {
  notify("Report ready");
  return HtmlService.createHtmlOutput("Done");
}

function notify(message) {
  SpreadsheetApp.getUi().alert(message);
}
Prefer 1 changed line
function doGet() {
  notify("Report ready");
  return HtmlService.createHtmlOutput("Done");
}

function notify(message) {
  console.log(message);
}
Tip 011 Avoids silent bug MF93011

Execute a web app as USER_ACCESSING when you need the visitor email

A web app deployed to execute as you returns an empty string from Session.getActiveUser().getEmail() unless the visitor is in your Google Workspace domain. Deploy it to execute as the user accessing it when you need the visitor's email.

Avoid 1 changed line
// appsscript.json: "webapp": { "executeAs": "USER_DEPLOYING" }
function doGet() {
  const email = Session.getActiveUser().getEmail();
  return HtmlService.createHtmlOutput("Hello " + email);
}
Prefer 1 changed line
// appsscript.json: "webapp": { "executeAs": "USER_ACCESSING" }
function doGet() {
  const email = Session.getActiveUser().getEmail();
  return HtmlService.createHtmlOutput("Hello " + email);
}
Tip 012 Avoids silent bug MF93012

Create installable triggers once from a setup function, not on every run

Simple triggers such as onOpen run without authorization, so creating a trigger from one fails. From doGet or doPost, each request adds another trigger until the project hits its limit of 20 per user. Create triggers from a menu item or a function you run once, or check getProjectTriggers() first.

Avoid 0 changed lines
function onOpen() {
  ScriptApp.newTrigger("sync").timeBased().everyHours(1).create();
}

function sync() {}
Prefer 4 changed lines
function onOpen() {
  SpreadsheetApp.getUi().createMenu("Sync").addItem("Turn on hourly sync", "installSync").addToUi();
}

function installSync() {
  ScriptApp.newTrigger("sync").timeBased().everyHours(1).create();
}

function sync() {}
Tip 013 Avoids silent bug MF93013

Read event properties like e.range and e.value without calling them

The event object Apps Script passes to onEdit, onOpen, doGet, and the other entry points holds plain values such as e.range, e.value, and e.parameter. Calling one, as in e.range(), throws "TypeError: e.range is not a function" when the trigger fires or the web app loads.

In myFunction: Remove the parentheses so the code reads the property.

Avoid 1 changed line
function onEdit(e) {
  e.range().setNote("Edited");
}
Prefer 1 changed line
function onEdit(e) {
  e.range.setNote("Edited");
}
Tip 014 Prevents runtime error MF93014

Keep doGet, doPost, google.script.run, and add-on callbacks synchronous

doGet(), doPost(), server functions called by google.script.run, and CardService add-on callbacks return values directly to Apps Script. Marking one async makes it return a Promise, which Apps Script does not await. Regular async functions and void triggers are allowed and are not flagged.

In myFunction: Remove async (and await on synchronous Apps Script calls).

Avoid 2 changed lines
async function doGet(e) {
  const response = await UrlFetchApp.fetch("https://api.example.com/status");
  return ContentService.createTextOutput(response.getContentText());
}
Prefer 2 changed lines
function doGet(e) {
  const response = UrlFetchApp.fetch("https://api.example.com/status");
  return ContentService.createTextOutput(response.getContentText());
}
Tip 015 Avoids silent bug MF93015

Wrap async entry points in try/catch and attach .catch() to Promises

Apps Script has no unhandledRejection error reporting, so a rejected Promise in an async entry point without try/catch or a detached .then() chain without .catch() fails silently.

Avoid 2 changed lines
async function runSync() {
  const result = await fetchRemoteData();
  Logger.log(result);
}

async function fetchRemoteData() {
  return Promise.resolve("ok");
}
Prefer 6 changed lines
async function runSync() {
  try {
    const result = await fetchRemoteData();
    Logger.log(result);
  } catch (error) {
    console.error(error);
  }
}

async function fetchRemoteData() {
  return Promise.resolve("ok");
}
Tip 016 Avoids silent bug MF93016

Read query params from e.parameter in doGet(), not e.postData

HTTP GET requests have no request body, so e.postData is never present in doGet(e). Read query parameters from e.parameter or e.parameters, or handle POST bodies in doPost(e).

Avoid 1 changed line
function doGet(e) {
  const payload = JSON.parse(e.postData.contents);
  return ContentService.createTextOutput(payload.id);
}
Prefer 1 changed line
function doPost(e) {
  const payload = JSON.parse(e.postData.contents);
  return ContentService.createTextOutput(payload.id);
}
Tip 017 Avoids silent bug MF93017

Guard e.value and e.oldValue in onEdit() for multi-cell pastes and clears

In onEdit(e), e.value and e.oldValue are undefined when a user pastes or clears multiple cells, and e.value is undefined when a single cell is cleared. Check for undefined or single-cell range dimensions before using them, or read e.range.getValues().

Avoid 0 changed lines
function onEdit(e) {
  e.range.setNote("New value: " + e.value.trim());
}
Prefer 1 changed line
function onEdit(e) {
  if (e.value === undefined) return;
  e.range.setNote("New value: " + e.value.trim());
}
Tip 018 Prevents runtime error MF93018

Stay within valid bounds for everyHours, atHour, nearMinute, and atDate

ClockTriggerBuilder rejects out-of-range arguments at runtime: everyHours() accepts only 1, 2, 4, 6, 8, or 12; atHour() accepts 0 to 23; nearMinute() accepts 0 to 59; onMonthDay() accepts 1 to 31; atDate(year, month, day) uses a 1-based month from 1 to 12; and everyDays(), everyWeeks(), and after() require at least 1.

In myFunction: Replace the argument with a supported value when unambiguous.

Avoid 1 changed line
function installTrigger() {
  ScriptApp.newTrigger("syncRows").timeBased().everyHours(3).create();
}

function syncRows() {}
Prefer 1 changed line
function installTrigger() {
  ScriptApp.newTrigger("syncRows").timeBased().everyHours(4).create();
}

function syncRows() {}
Tip 019 Avoids silent bug MF93019

End every ScriptApp.newTrigger() chain with .create()

ScriptApp.newTrigger() returns a trigger builder that does nothing until .create() is called. A discarded trigger builder statement leaves no trigger installed.

In myFunction: Append .create().

Avoid 1 changed line
function installTrigger() {
  ScriptApp.newTrigger("syncRows").timeBased().everyHours(1);
}

function syncRows() {}
Prefer 1 changed line
function installTrigger() {
  ScriptApp.newTrigger("syncRows").timeBased().everyHours(1).create();
}

function syncRows() {}
Tip 020 Avoids silent bug MF93020

Check e.authMode before reading document state inside an add-on onOpen()

In an Editor Add-on, onOpen(e) runs in ScriptApp.AuthMode.NONE before the add-on is enabled for the current document. Calling PropertiesService, CacheService, LockService, Session, or active document methods without checking e.authMode throws an authorization error.

Avoid 5 changed lines
function onOpen(e) {
  const enabled = PropertiesService.getDocumentProperties().getProperty("enabled");
  SpreadsheetApp.getUi()
    .createAddonMenu()
    .addItem(enabled ? "Refresh" : "Setup", "runAddon")
    .addToUi();
}

function runAddon() {}
Prefer 8 changed lines
function onOpen(e) {
  const menu = SpreadsheetApp.getUi().createAddonMenu();
  if (e && e.authMode === ScriptApp.AuthMode.NONE) {
    menu.addItem("Setup", "runAddon");
  } else {
    const enabled = PropertiesService.getDocumentProperties().getProperty("enabled");
    menu.addItem(enabled ? "Refresh" : "Setup", "runAddon");
  }
  menu.addToUi();
}

function runAddon() {}
Tip 021 Prevents runtime error MF93021

Call .build() before returning a CardService builder

CardService builder classes such as CardBuilder and ActionResponseBuilder must be finalized with .build() before returning them from a Google Workspace Add-on callback.

In myFunction: Append .build().

Avoid 3 changed lines
function onHomepage() {
  return CardService.newCardBuilder().setHeader(
    CardService.newCardHeader().setTitle("Overview"),
  );
}
Prefer 3 changed lines
function onHomepage() {
  return CardService.newCardBuilder()
    .setHeader(CardService.newCardHeader().setTitle("Overview"))
    .build();
}

13 tips

Ranges and Sheets data

Prevent off-by-one coordinates, shape mismatches, and locale formula errors.

Tip 022 Prevents runtime error MF94001

Start getRange() row, column, and dimension counts at 1, not 0

Rows and columns start at 1, and a range needs at least one row and one column. Sheet.getRange(0, 1) or a literal 0 for numRows throws "The coordinates or dimensions of the range are invalid."

In myFunction: Change a 0 row or column to 1.

Avoid 1 changed line
function readHeader() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange(0, 1, 1, 5).getValues();
}
Prefer 1 changed line
function readHeader() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange(1, 1, 1, 5).getValues();
}
Tip 023 Prevents runtime error MF94002

Match the 2D array row and column counts to your target range in setValues()

setValues() and the other 2D setters need exactly one row of data per range row and one value per column. When getRange() has literal dimensions or A1 notation and the data is an array literal, a different row count throws "The number of rows in the data does not match the number of rows in the range." A different column count, or rows of uneven length, throws the same error for columns.

In myFunction: Size getRange() to the rows and columns of the data.

Avoid 1 changed line
function writeHeader() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, 1, 3).setValues([["Name", "Email"]]);
}
Prefer 1 changed line
function writeHeader() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, 1, 2).setValues([["Name", "Email"]]);
}
Tip 024 Avoids silent bug MF94003

Return early before reading rows when getLastRow() can be 0 or 1

getRange(2, 1, sheet.getLastRow() - 1, n) asks for zero rows on a sheet that holds only a header, and getRange() throws "The number of rows in the range must be at least 1." The rule stays quiet when the function compares the last row before reading. getLastColumn() counts are checked the same way.

In myFunction: Return early when the sheet has nothing past the header, in functions that return no value.

Avoid 0 changed lines
function readRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const rows = sheet.getRange(2, 1, sheet.getLastRow() - 1, 3).getValues();
  Logger.log(rows.length);
}
Prefer 1 changed line
function readRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  if (sheet.getLastRow() <= 1) return;
  const rows = sheet.getRange(2, 1, sheet.getLastRow() - 1, 3).getValues();
  Logger.log(rows.length);
}
Tip 025 Avoids silent bug MF94004

Pass a row count to getRange(), not the ending row from getLastRow()

The third argument of getRange() is a number of rows, not the last row. Starting at row 2 with getLastRow() rows reads one row past the data, and the extra rows come back as empty strings.

In myFunction: Subtract the rows above the start row.

Avoid 1 changed line
function readRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange(2, 1, sheet.getLastRow(), 3).getValues();
}
Prefer 1 changed line
function readRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange(2, 1, sheet.getLastRow() - 1, 3).getValues();
}
Tip 026 Avoids silent bug MF94005

Iterate backward when deleting rows or columns in a loop

deleteRow() moves every later row up by one. In a loop that counts up, the row after each deleted one is never visited. The rule stays quiet when the loop corrects the index, for example with i--.

In myFunction: Reverse the loop so it counts down.

Avoid 1 changed line
function removeDone() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const values = sheet.getDataRange().getValues();
  for (let i = 1; i < values.length; i++) {
    if (values[i][0] === "Done") sheet.deleteRow(i + 1);
  }
}
Prefer 1 changed line
function removeDone() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const values = sheet.getDataRange().getValues();
  for (let i = values.length - 1; i >= 1; i--) {
    if (values[i][0] === "Done") sheet.deleteRow(i + 1);
  }
}
Tip 027 Avoids silent bug MF94006

Use setValues() instead of setValue() when writing an array

Range.setValue() writes a single cell and coerces an array into a string instead of filling multiple cells. TypeScript does not reject this because setValue() accepts unknown. Use setValues() with a 2D array to write a grid.

In myFunction: Switch to setValues(), wrapping a 1D array literal as a single row.

Avoid 1 changed line
function writeHeader() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange("A1:B1").setValue(["Name", "Email"]);
}
Prefer 1 changed line
function writeHeader() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange("A1:B1").setValues([["Name", "Email"]]);
}
Tip 028 Prevents runtime error MF94007

Quote sheet names with spaces and check A1 bounds in getRange()

getRange() and getRangeList() throw at runtime when an A1 notation string has row 0, a bad range separator such as ';', an empty cell reference, or an unquoted sheet name containing spaces or special characters.

In myFunction: Wrap an unquoted sheet name in single quotes.

Avoid 1 changed line
function readTotal() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  return ss.getRange("My Sheet!A1:B5").getValues();
}
Prefer 1 changed line
function readTotal() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  return ss.getRange("'My Sheet'!A1:B5").getValues();
}
Tip 029 Best practice MF94008

Qualify the sheet name when calling getRange() on a Spreadsheet object

Calling getRange() directly on a Spreadsheet without a SheetName! prefix silently targets whichever sheet happens to be active. Prefix the sheet name or call getRange() on a specific Sheet.

Avoid 1 changed line
function readSummary() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  return ss.getRange("A1:B5").getValues();
}
Prefer 1 changed line
function readSummary() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  return ss.getRange("Summary!A1:B5").getValues();
}
Tip 030 Avoids silent bug MF94009

Write US-English function names and comma separators in setFormula()

setFormula() and setFormulas() always expect US-locale formula syntax regardless of the spreadsheet locale, using commas between arguments and English function names. Semicolons inside array literals and quoted strings are allowed.

Avoid 1 changed line
function setTotalFormula() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange("C1").setFormula("=SUMME(A1; B1)");
}
Prefer 1 changed line
function setTotalFormula() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange("C1").setFormula("=SUM(A1, B1)");
}
Tip 031 Best practice MF94010

Use setFormula() for formulas and neutralize untrusted cell input

setValue() and setValues() parse strings starting with '=' as formulas. Use setFormula() or setFormulas() for intentional formulas, or prefix literal text with a single quote. Writing web or form input (e.parameter or e.values) directly to setValue(), setValues(), or appendRow() escalates to a warning for formula injection.

Avoid 1 changed line
function writeTotal() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange("C1").setValue("=SUM(A1:B1)");
}
Prefer 1 changed line
function writeTotal() {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange("C1").setFormula("=SUM(A1:B1)");
}
Tip 032 Avoids silent bug MF94011

Use getLastRow() and getLastColumn() instead of getMaxRows() when reading data

getMaxRows() and getMaxColumns() include every empty trailing row or column allocated on the sheet, making getValues() and other reads slow and memory-heavy. Structural calls such as deleteRows() or clearFormat() are not flagged.

In myFunction: Replace getMaxRows() with getLastRow(), or getMaxColumns() with getLastColumn().

Avoid 1 changed line
function readAllRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange(1, 1, sheet.getMaxRows(), 3).getValues();
}
Prefer 1 changed line
function readAllRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange(1, 1, sheet.getLastRow(), 3).getValues();
}
Tip 033 Prevents runtime error MF94012

Copy across spreadsheets with getValues()/setValues(), not Range.copyTo()

Range.copyTo() only copies within the same spreadsheet and throws at runtime when source and destination belong to different spreadsheets. Read values with getValues() and write them to the destination range with setValues().

Avoid 3 changed lines
function copySummary() {
  const src = SpreadsheetApp.getActiveSheet().getRange("A1:B5");
  const dst = SpreadsheetApp.openById("TARGET_ID").getSheets()[0].getRange("A1:B5");
  src.copyTo(dst);
}
Prefer 2 changed lines
function copySummary() {
  const values = SpreadsheetApp.getActiveSheet().getRange("A1:B5").getValues();
  SpreadsheetApp.openById("TARGET_ID").getSheets()[0].getRange("A1:B5").setValues(values);
}
Tip 034 Avoids silent bug MF92004

Loop over getValues() rows with for, for...of, or forEach(), not for...in

for...in yields each array index as a string, so with rows from getValues(), i + 2 is "02" and a getRange() row computed from it is wrong. It can also visit properties that are not elements. Use a counting for loop, for...of, or forEach().

In myFunction: Rewrite as a counting for loop over the array's length.

Avoid 1 changed line
function logRows() {
  const rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
  for (var i in rows) {
    Logger.log("Row " + (i + 1) + ": " + rows[i][0]);
  }
}
Prefer 1 changed line
function logRows() {
  const rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
  for (var i = 0; i < rows.length; i++) {
    Logger.log("Row " + (i + 1) + ": " + rows[i][0]);
  }
}

21 tips

Services, quotas, and security

Handle UrlFetchApp, Properties, Cache, LockService, Drive, Mail, and JDBC reliably.

Tip 035 Avoids silent bug MF95001

Call JSON.stringify() on object payloads when sending JSON with UrlFetchApp

When payload is an object, UrlFetchApp encodes it as form fields (a=1&b=2), whatever contentType says. An API expecting JSON then rejects the request.

In myFunction: Wrap the payload in JSON.stringify().

Avoid 1 changed line
function createItem() {
  UrlFetchApp.fetch("https://example.com/items", {
    method: "post",
    contentType: "application/json",
    payload: { name: "New item" },
  });
}
Prefer 1 changed line
function createItem() {
  UrlFetchApp.fetch("https://example.com/items", {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify({ name: "New item" }),
  });
}
Tip 036 Avoids silent bug MF95002

Use yyyy, MM, and dd in Utilities.formatDate() instead of YYYY, mm, or DD

Utilities.formatDate() patterns follow Java SimpleDateFormat. YYYY is the week year, which is off by one for some dates around January 1. DD is the day of the year, and mm is minutes, so dd/mm/yyyy prints the minutes where the month should be.

In myFunction: Use yyyy, dd, and MM.

Avoid 1 changed line
function stamp() {
  return Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/mm/YYYY");
}
Prefer 1 changed line
function stamp() {
  return Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy");
}
Tip 037 Prevents runtime error MF95003

Keep Utilities.sleep() at or below 300000 ms (5 minutes)

Utilities.sleep() accepts at most 300000 milliseconds. A longer wait needs a time-driven trigger.

In myFunction: Use 300000.

Avoid 1 changed line
function waitAndRetry() {
  Utilities.sleep(600000);
}
Prefer 1 changed line
function waitAndRetry() {
  Utilities.sleep(300000);
}
Tip 038 Prevents runtime error MF95004

Keep CacheService expiration between 1 and 21600 seconds (6 hours)

Cache entries last at most 6 hours. put() and putAll() reject an expiration above 21600 seconds or below 1.

In myFunction: Use the nearest allowed expiration.

Avoid 1 changed line
function remember(value) {
  CacheService.getScriptCache().put("latest", value, 86400);
}
Prefer 1 changed line
function remember(value) {
  CacheService.getScriptCache().put("latest", value, 21600);
}
Tip 039 Avoids silent bug MF95005

Check hasNext() before calling next() on DriveApp iterators

DriveApp.getFilesByName() and similar calls return an iterator. Calling next() when nothing matches throws, so a renamed or missing file stops the script with an error that does not name the file.

In myFunction: Store the iterator and throw a clear error when hasNext() is false.

Avoid 1 changed line
function reportName() {
  return DriveApp.getFilesByName("Report").next().getName();
}
Prefer 3 changed lines
function reportName() {
  const files = DriveApp.getFilesByName("Report");
  if (!files.hasNext()) throw new Error("No file named Report.");
  return files.next().getName();
}
Tip 040 Avoids silent bug MF95006

Check getResponseCode() whenever muteHttpExceptions is true

With muteHttpExceptions: true, UrlFetchApp returns 4xx and 5xx responses instead of throwing. Code that reads the body without calling getResponseCode() treats an error page as data.

In myFunction: Throw when the status is 400 or above, with the response body in the message.

Avoid 0 changed lines
function fetchItems(url) {
  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
  return JSON.parse(response.getContentText());
}
Prefer 3 changed lines
function fetchItems(url) {
  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
  if (response.getResponseCode() >= 400) {
    throw new Error("Request failed with status " + response.getResponseCode() + ": " + response.getContentText());
  }
  return JSON.parse(response.getContentText());
}
Tip 041 Avoids silent bug MF95007

Check the boolean returned by tryLock(), or switch to waitLock()

tryLock() returns false when another run holds the lock past the timeout. If the result is not checked, the code after it runs without the lock it was meant to have.

In myFunction: Use waitLock(), which throws when the lock is not available in time.

Avoid 1 changed line
function addRow(values) {
  const lock = LockService.getScriptLock();
  lock.tryLock(10000);
  try {
    SpreadsheetApp.getActiveSheet().appendRow(values);
  } finally {
    lock.releaseLock();
  }
}
Prefer 1 changed line
function addRow(values) {
  const lock = LockService.getScriptLock();
  lock.waitLock(10000);
  try {
    SpreadsheetApp.getActiveSheet().appendRow(values);
  } finally {
    lock.releaseLock();
  }
}
Tip 042 Best practice MF95008

Release every LockService lock inside a finally block

A lock from waitLock() or tryLock() is held until the script finishes when the function never calls releaseLock(). Other runs wait for that whole time. Release it in a finally block so an error does not keep it held either.

Avoid 1 changed line
function addRow(values) {
  const lock = LockService.getScriptLock();
  lock.waitLock(10000);
  SpreadsheetApp.getActiveSheet().appendRow(values);
  sendSummary();
}

function sendSummary() {}
Prefer 5 changed lines
function addRow(values) {
  const lock = LockService.getScriptLock();
  lock.waitLock(10000);
  try {
    SpreadsheetApp.getActiveSheet().appendRow(values);
  } finally {
    lock.releaseLock();
  }
  sendSummary();
}

function sendSummary() {}
Tip 043 Avoids silent bug MF95009

Store API keys and tokens in PropertiesService, not in source files

A string that looks like an API key, access token, or bearer token is readable by anyone who can view or copy the project, and it stays in the version history after you delete it. Keep it in Script Properties and read it with PropertiesService. The message never repeats the value.

In myFunction: Read the value from Script Properties; add the property under Project Settings and rotate the old key.

Avoid 1 changed line
function getOrders() {
  const response = UrlFetchApp.fetch("https://api.example.com/orders", {
    headers: { Authorization: "Bearer 3f9a7c2e1b8d4f6a0c5e9b7d2a4f8c1e" },
  });
  return JSON.parse(response.getContentText());
}
Prefer 1 changed line
function getOrders() {
  const response = UrlFetchApp.fetch("https://api.example.com/orders", {
    headers: { Authorization: "Bearer " + PropertiesService.getScriptProperties().getProperty("API_TOKEN") },
  });
  return JSON.parse(response.getContentText());
}
Tip 044 Best practice MF95010

Wrap dynamic query parameter values in encodeURIComponent()

A value placed after ?name= or &name= in a fetched URL goes in as typed. A space, &, #, or accented letter in it breaks the request or changes which parameters the server sees. Wrap the value in encodeURIComponent().

In myFunction: Wrap the value in encodeURIComponent().

Avoid 1 changed line
function search(term) {
  return UrlFetchApp.fetch("https://api.example.com/search?q=" + term);
}
Prefer 1 changed line
function search(term) {
  return UrlFetchApp.fetch("https://api.example.com/search?q=" + encodeURIComponent(term));
}
Tip 045 Best practice MF95011

Pass Session.getScriptTimeZone() to formatDate() instead of hard-coding a zone

A time zone written into Utilities.formatDate() stays fixed when the project's time zone in appsscript.json changes, and it disagrees with it now. Session.getScriptTimeZone() follows the manifest. UTC and GMT offsets are not flagged.

In myFunction: Use Session.getScriptTimeZone().

Avoid 1 changed line
// appsscript.json: "timeZone": "Europe/London"
function label(date) {
  return Utilities.formatDate(date, "America/New_York", "yyyy-MM-dd");
}
Prefer 1 changed line
// appsscript.json: "timeZone": "Europe/London"
function label(date) {
  return Utilities.formatDate(date, Session.getScriptTimeZone(), "yyyy-MM-dd");
}
Tip 046 Avoids silent bug MF95012

Respect the 9 KB PropertiesService limit and 100 KB / 250-character CacheService limits

PropertiesService caps each value at 9 KB (and 500 KB total), and CacheService caps keys at 250 characters and values at 100 KB. Literal values over those limits, or passing JSON.stringify(sheet.getDataRange().getValues()) directly to setProperty(), throw at runtime.

Avoid 1 changed line
function backupSheet() {
  const sheet = SpreadsheetApp.getActiveSheet();
  PropertiesService.getScriptProperties().setProperty("rows", JSON.stringify(sheet.getDataRange().getValues()));
}
Prefer 1 changed line
function backupSheet() {
  const sheet = SpreadsheetApp.getActiveSheet();
  DriveApp.createFile("rows.json", JSON.stringify(sheet.getDataRange().getValues()), "application/json");
}
Tip 047 Avoids silent bug MF95013

Guard PropertiesService.getDocumentProperties() against null in web apps

PropertiesService.getDocumentProperties() returns null in standalone scripts. Calling methods on it inside doGet() or doPost() without a null check throws a TypeError unless the script is bound to a document.

Avoid 1 changed line
function doGet() {
  const props = PropertiesService.getDocumentProperties();
  return ContentService.createTextOutput(props.getProperty("mode") ?? "");
}
Prefer 1 changed line
function doGet() {
  const props = PropertiesService.getScriptProperties();
  return ContentService.createTextOutput(props.getProperty("mode") ?? "");
}
Tip 048 Avoids silent bug MF95014

Use UrlFetchApp option names like payload and followRedirects, not Fetch API names

UrlFetchApp ignores Fetch API option names such as body, redirect, mode, credentials, and capitalized ContentType. Requests silently drop the body or send the wrong content type.

In myFunction: Rename body to payload or ContentType to contentType.

Avoid 2 changed lines
function postItem(url, data) {
  const options = {
    method: "post",
    ContentType: "application/json",
    body: JSON.stringify(data),
  };
  return UrlFetchApp.fetch(url, options);
}
Prefer 2 changed lines
function postItem(url, data) {
  const options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(data),
  };
  return UrlFetchApp.fetch(url, options);
}
Tip 049 Avoids silent bug MF95015

Do not send a payload with an explicit GET request in UrlFetchApp

UrlFetchApp rejects or drops request bodies when method is explicitly set to get. When method is omitted alongside payload, UrlFetchApp sends a POST automatically, so only explicit GET with payload is flagged.

Avoid 2 changed lines
function search(url, term) {
  return UrlFetchApp.fetch(url, {
    method: "get",
    payload: { q: term },
  });
}
Prefer 1 changed line
function search(url, term) {
  return UrlFetchApp.fetch(url + "?q=" + encodeURIComponent(term), {
    method: "get",
  });
}
Tip 050 Avoids silent bug MF95016

Keep TLS certificate verification enabled in UrlFetchApp requests

Setting validateHttpsCertificates: false in UrlFetchApp disables HTTPS certificate checks and exposes the request and any credentials in it to interception.

Avoid 1 changed line
function loadFeed(url) {
  return UrlFetchApp.fetch(url, { validateHttpsCertificates: false }).getContentText();
}
Prefer 1 changed line
function loadFeed(url) {
  return UrlFetchApp.fetch(url).getContentText();
}
Tip 051 Prevents runtime error MF95017

Send ScriptApp.getOAuthToken() only to Google API hosts

ScriptApp.getOAuthToken() returns a bearer token authorized for your Google account and script scopes. Sending it via UrlFetchApp to a non-Google host leaks that access token to a third party.

Avoid 1 changed line
function syncData() {
  return UrlFetchApp.fetch("https://api.example.com/sync", {
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
  });
}
Prefer 2 changed lines
function syncData() {
  const key = PropertiesService.getScriptProperties().getProperty("EXAMPLE_API_KEY");
  return UrlFetchApp.fetch("https://api.example.com/sync", {
    headers: { Authorization: "Bearer " + key },
  });
}
Tip 052 Best practice MF95018

Close JDBC connections, statements, and result sets in a finally block

Jdbc.getConnection(), prepareStatement(), and executeQuery() hold database connections and cursors open until closed. Leaving them unclosed can exhaust connection pool limits.

Avoid 1 changed line
function countUsers(url) {
  const conn = Jdbc.getConnection(url);
  const stmt = conn.prepareStatement("SELECT COUNT(*) FROM users");
  const rs = stmt.executeQuery();
  return rs.next() ? rs.getInt(1) : 0;
}
Prefer 7 changed lines
function countUsers(url) {
  const conn = Jdbc.getConnection(url);
  const stmt = conn.prepareStatement("SELECT COUNT(*) FROM users");
  const rs = stmt.executeQuery();
  try {
    return rs.next() ? rs.getInt(1) : 0;
  } finally {
    rs.close();
    stmt.close();
    conn.close();
  }
}
Tip 053 Avoids silent bug MF95019

Use Jdbc prepareStatement() placeholders instead of string concatenation

Concatenating or interpolating dynamic values into executeQuery(), executeUpdate(), or execute() exposes the database to SQL injection. Use prepareStatement() with ? placeholders and bind values with setString() or setInt().

Avoid 2 changed lines
/** @param {Jdbc.JdbcConnection} conn */
function findUser(conn, email) {
  const stmt = conn.createStatement();
  try {
    const rs = stmt.executeQuery("SELECT * FROM users WHERE email = '" + email + "'");
    try {
      return rs.next();
    } finally {
      rs.close();
    }
  } finally {
    stmt.close();
  }
}
Prefer 3 changed lines
/** @param {Jdbc.JdbcConnection} conn */
function findUser(conn, email) {
  const stmt = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
  try {
    stmt.setString(1, email);
    const rs = stmt.executeQuery();
    try {
      return rs.next();
    } finally {
      rs.close();
    }
  } finally {
    stmt.close();
  }
}
Tip 054 Avoids silent bug MF95020

Pass HTML emails in options.htmlBody instead of the plain-text body argument

The third positional argument to MailApp.sendEmail() and GmailApp.sendEmail() is plain text, so tags like <h1> or <p> arrive as literal text. Pass HTML in the options object under htmlBody instead.

In myFunction: Move the HTML markup into { htmlBody: ... }.

Avoid 1 changed line
function sendWelcome(to) {
  MailApp.sendEmail(to, "Welcome", "<h1>Welcome</h1><p>Your account is ready.</p>");
}
Prefer 1 changed line
function sendWelcome(to) {
  MailApp.sendEmail(to, "Welcome", "", { htmlBody: "<h1>Welcome</h1><p>Your account is ready.</p>" });
}
Tip 055 Best practice MF95021

Include supportsAllDrives: true on Drive v3 calls that touch Shared Drives

Advanced Drive v3 calls such as Drive.Files.get(), list(), update(), copy(), remove(), and Drive.Permissions.create() ignore Shared Drive files unless supportsAllDrives: true is passed (and includeItemsFromAllDrives: true on list()).

In myFunction: Add supportsAllDrives: true (and includeItemsFromAllDrives: true on list()).

Avoid 1 changed line
function listReports() {
  return Drive.Files.list({ q: "trashed = false" });
}
Prefer 1 changed line
function listReports() {
  return Drive.Files.list({ q: "trashed = false", supportsAllDrives: true, includeItemsFromAllDrives: true });
}

2 tips

Removed and deprecated APIs

Replace retired services and methods before they fail at runtime.

Tip 056 Prevents runtime error MF98001

Replace shut-down services like UiApp, DocsList, and ContactsApp

UiApp, DocsList, ScriptDb, FinanceApp, and ContactsApp no longer run. Code that calls them fails, even where the editor still knows their names. Each message names the replacement, such as HtmlService for UiApp and the People advanced service for ContactsApp.

Avoid 2 changed lines
function showDialog() {
  const app = UiApp.createApplication();
  return app;
}
Prefer 1 changed line
function showDialog() {
  SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutput("<p>Hello</p>"), "Hello");
}
Tip 057 Avoids silent bug MF98002

Migrate deprecated methods like DriveApp.addFile() and Session.getTimeZone()

Session.getTimeZone(), Session.getUser(), ScriptApp.getProjectKey(), Utilities.jsonParse(), Utilities.jsonStringify(), and the multi-parent DriveApp/Folder addFile/removeFile/addFolder/removeFolder methods are deprecated. Each message names the replacement.

In myFunction: Replace direct 1:1 deprecated calls with their successor.

Avoid 1 changed line
function zone() {
  return Session.getTimeZone();
}
Prefer 1 changed line
function zone() {
  return Session.getScriptTimeZone();
}

16 tips

Performance and batching

Cut service round trips and stay well under the 6-minute execution limit.

Tip 058 Avoids silent bug MF90001

Batch range reads with getValues() instead of calling getValue() in a loop

Calling getValue() or another single-cell getter on each pass of a loop, or in a forEach() or map() callback, makes one service call per cell. Reading the block once with the plural getter is much faster.

In myFunction: Read the range once with the plural getter before the loop, when the loop shape allows it.

Avoid 3 changed lines
function total() {
  const range = SpreadsheetApp.getActiveSheet().getRange(1, 1, 10, 1);
  let sum = 0;
  for (let row = 1; row <= 10; row++) {
    sum += range.getCell(row, 1).getValue();
  }
  return sum;
}
Prefer 3 changed lines
function total() {
  const values = SpreadsheetApp.getActiveSheet().getRange(1, 1, 10, 1).getValues();
  let sum = 0;
  for (let row = 0; row < values.length; row++) {
    sum += values[row][0];
  }
  return sum;
}
Tip 059 Avoids silent bug MF90002

Collect rows in memory and call setValues() once after the loop

Calling setValue() or another single-cell setter on each pass of a loop, or in a forEach() or map() callback, makes one service call per cell. Collecting a 2D array and writing it once is much faster.

In myFunction: Collect the values and write the range once with the plural setter, when the loop shape allows it.

Avoid 1 changed line
function fill() {
  const range = SpreadsheetApp.getActiveSheet().getRange(1, 1, 10, 1);
  for (let row = 1; row <= 10; row++) {
    range.getCell(row, 1).setValue(row * 2);
  }
}
Prefer 3 changed lines
function fill() {
  const range = SpreadsheetApp.getActiveSheet().getRange(1, 1, 10, 1);
  const grid = [];
  for (let row = 1; row <= 10; row++) {
    grid.push([row * 2]);
  }
  range.setValues(grid);
}
Tip 060 Avoids silent bug MF90003

Move SpreadsheetApp.flush() outside loops

flush() forces pending changes to the server. Inside a loop it repeats that round trip on every pass.

In myFunction: Guidance on when flush() can move after the loop.

Avoid 1 changed line
function mark(rows) {
  const sheet = SpreadsheetApp.getActiveSheet();
  for (const row of rows) {
    sheet.getRange(row, 1).setNote("done");
    SpreadsheetApp.flush();
  }
}
Prefer 1 changed line
function mark(rows) {
  const sheet = SpreadsheetApp.getActiveSheet();
  for (const row of rows) {
    sheet.getRange(row, 1).setNote("done");
  }
  SpreadsheetApp.flush();
}
Tip 061 Avoids silent bug MF90004

Batch independent HTTP calls with UrlFetchApp.fetchAll()

Each fetch() waits for the previous request to finish. UrlFetchApp.fetchAll() sends independent requests together.

In myFunction: Guidance on when fetchAll() gives the same result as the loop.

Avoid 5 changed lines
function fetchAll(urls) {
  const bodies = [];
  for (const url of urls) {
    bodies.push(UrlFetchApp.fetch(url).getContentText());
  }
  return bodies;
}
Prefer 1 changed line
function fetchAll(urls) {
  return UrlFetchApp.fetchAll(urls).map((response) => response.getContentText());
}
Tip 062 Avoids silent bug MF90008

Pass start and max arguments to GmailApp.search() and thread getters

GmailApp.search(query), getInboxThreads(), and similar calls without a start and max return every matching thread, and Google notes they fail when the threads are too large to handle. Pass a start and max and page through the results.

In myFunction: Add a start of 0 and a max of 100.

Avoid 1 changed line
function countInvoices() {
  return GmailApp.search("subject:invoice").length;
}
Prefer 1 changed line
function countInvoices() {
  return GmailApp.search("subject:invoice", 0, 100).length;
}
Tip 063 Avoids silent bug MF90009

Hoist openById(), getSheetByName(), and getActiveSheet() above loops

openById(), getSheetByName(), getFileById(), and active-container or UI getters such as getActiveSheet(), getActiveSpreadsheet(), getUi(), and getBody() return the same object on every pass. Inside a loop they repeat the service call unnecessarily.

In myFunction: Move the const above the loop.

Avoid 1 changed line
function stampRows(rows) {
  const ss = SpreadsheetApp.getActive();
  for (const row of rows) {
    const log = ss.getSheetByName("Log");
    log.getRange(row, 2).setValue(new Date());
  }
}
Prefer 1 changed line
function stampRows(rows) {
  const ss = SpreadsheetApp.getActive();
  const log = ss.getSheetByName("Log");
  for (const row of rows) {
    log.getRange(row, 2).setValue(new Date());
  }
}
Tip 064 Avoids silent bug MF90010

Build a 2D array and write with setValues() instead of appendRow() in a loop

Each appendRow() is a separate call to Sheets. Collecting the rows and writing them with one setValues() call is much faster for more than a few rows.

Avoid 1 changed line
function logOrders(orders) {
  const sheet = SpreadsheetApp.getActiveSheet();
  orders.forEach((order) => sheet.appendRow([order.id, order.total]));
}
Prefer 2 changed lines
function logOrders(orders) {
  const sheet = SpreadsheetApp.getActiveSheet();
  const rows = orders.map((order) => [order.id, order.total]);
  if (rows.length > 0) sheet.getRange(sheet.getLastRow() + 1, 1, rows.length, 2).setValues(rows);
}
Tip 065 Best practice MF90011

Cache sheet.getLastRow() in a variable instead of calling it in the loop condition

A for or while condition runs before every pass, so sheet.getLastRow() there asks Sheets again each time. The rule stays quiet when the loop body writes to the sheet or calls project functions, since the value may then change.

In myFunction: Read the value into a const before the loop.

Avoid 1 changed line
function logRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  for (let row = 2; row <= sheet.getLastRow(); row++) {
    Logger.log(row);
  }
}
Prefer 2 changed lines
function logRows() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const lastRow = sheet.getLastRow();
  for (let row = 2; row <= lastRow; row++) {
    Logger.log(row);
  }
}
Tip 066 Avoids silent bug MF90012

Batch PropertiesService access with getProperties() and setProperties()

getProperty() and setProperty() each call the Properties service. In a loop, read every value once with getProperties() and write changes together with setProperties().

Avoid 4 changed lines
function saveTotals(totals) {
  const props = PropertiesService.getScriptProperties();
  for (const name of Object.keys(totals)) {
    props.setProperty(name, String(totals[name]));
  }
}
Prefer 3 changed lines
function saveTotals(totals) {
  const values = {};
  for (const name of Object.keys(totals)) values[name] = String(totals[name]);
  PropertiesService.getScriptProperties().setProperties(values);
}
Tip 067 Avoids silent bug MF90013

Batch CacheService access with getAll(), putAll(), and removeAll()

get(), put(), and remove() each call the Cache service. getAll(), putAll(), and removeAll() handle many keys in one call.

Avoid 2 changed lines
function cachedNames(ids) {
  const cache = CacheService.getScriptCache();
  return ids.map((id) => cache.get("name:" + id));
}
Prefer 3 changed lines
function cachedNames(ids) {
  const keys = ids.map((id) => "name:" + id);
  const values = CacheService.getScriptCache().getAll(keys);
  return keys.map((key) => values[key]);
}
Tip 068 Best practice MF90014

Check MailApp.getRemainingDailyQuota() when sending emails in a loop

Apps Script allows 100 email recipients a day on a consumer account and 1,500 on Google Workspace. A loop that sends mail without checking MailApp.getRemainingDailyQuota() fails partway through the list once the quota runs out.

Avoid 0 changed lines
function notify(addresses) {
  for (const address of addresses) {
    MailApp.sendEmail(address, "Report ready", "The weekly report is ready.");
  }
}
Prefer 1 changed line
function notify(addresses) {
  for (const address of addresses) {
    if (MailApp.getRemainingDailyQuota() === 0) throw new Error("Daily email quota used up at " + address);
    MailApp.sendEmail(address, "Report ready", "The weekly report is ready.");
  }
}
Tip 069 Avoids silent bug MF90016

Add trashed = false to DriveApp.searchFiles() and searchFolders() queries

DriveApp.searchFiles() and searchFolders() return items in the trash by default unless the query specifies trashed = false.

In myFunction: Append 'and trashed = false' to the query.

Avoid 1 changed line
function findPdfs() {
  return DriveApp.searchFiles("mimeType = 'application/pdf'");
}
Prefer 1 changed line
function findPdfs() {
  return DriveApp.searchFiles("mimeType = 'application/pdf' and trashed = false");
}
Tip 070 Avoids silent bug MF90017

Fetch messages in one call with GmailApp.getMessagesForThreads(threads)

Calling getMessages() on each GmailThread inside a loop makes one Gmail service call per thread. Batch all threads in a single call with GmailApp.getMessagesForThreads(threads).

Avoid 2 changed lines
function listSubjects() {
  const threads = GmailApp.search("is:unread", 0, 50);
  for (const thread of threads) {
    Logger.log(thread.getMessages().length);
  }
}
Prefer 3 changed lines
function listSubjects() {
  const threads = GmailApp.search("is:unread", 0, 50);
  const messageGroups = GmailApp.getMessagesForThreads(threads);
  for (const messages of messageGroups) {
    Logger.log(messages.length);
  }
}
Tip 071 Best practice MF90018

Use continuation tokens or a limit when iterating root DriveApp.getFiles()

Iterating root DriveApp.getFiles() or getFolders() in a while loop without a continuation token, break, or count limit walks every item in Drive and can exceed the 6-minute execution limit. Scoped calls such as folder.getFiles(), getFilesByName(), and searchFiles() are not flagged.

Avoid 1 changed line
function listAllFiles() {
  const files = DriveApp.getFiles();
  while (files.hasNext()) {
    Logger.log(files.next().getName());
  }
}
Prefer 3 changed lines
function listAllFiles() {
  const files = DriveApp.getFiles();
  let count = 0;
  while (files.hasNext() && count < 100) {
    Logger.log(files.next().getName());
    count++;
  }
}
Tip 072 Avoids silent bug MF90019

Keep unconditional Utilities.sleep() out of data loops

Sleeping unconditionally on every iteration of a data loop burns execution time and risks hitting the 6-minute limit. Calls inside catch blocks, conditional throttles, or retry loops are not flagged.

Avoid 1 changed line
function processRows(rows) {
  for (const row of rows) {
    Logger.log(row);
    Utilities.sleep(1000);
  }
}
Prefer 0 changed lines
function processRows(rows) {
  for (const row of rows) {
    Logger.log(row);
  }
}
Tip 073 Best practice MF90015

Bound range reads to getLastRow() instead of open-ended ranges like A2:C

A range such as A2:C or A:A runs to the last row of the sheet, not the last row with data. getValues() then returns a row for every empty row too, often thousands of them, and loops over the result do the same.

In myFunction: End the range at getLastRow().

Avoid 1 changed line
function readOrders() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange("A2:C").getValues();
}
Prefer 1 changed line
function readOrders() {
  const sheet = SpreadsheetApp.getActiveSheet();
  return sheet.getRange("A2:C" + sheet.getLastRow()).getValues();
}

11 tips

Custom Sheets functions

Keep @customfunction formulas fast, synchronous, and free of #NAME? or #ERROR!.

Tip 074 Avoids silent bug MF91001

Keep services that require authorization out of @customfunction formulas

Functions marked @customfunction run without user authorization. GmailApp, DriveApp, CalendarApp, and similar services that need it fail inside a formula. UrlFetchApp is supported.

Avoid 2 changed lines
/** @customfunction */
function UNREAD() {
  return GmailApp.getInboxUnreadCount();
}
Prefer 2 changed lines
/** @customfunction */
function DOUBLE(value) {
  return value * 2;
}
Tip 075 Avoids silent bug MF91002

Return values from custom functions instead of mutating the sheet

A custom function can only return values. Calls such as setValue(), appendRow(), or insertSheet() fail when Sheets evaluates the formula.

Avoid 2 changed lines
/** @customfunction */
function STAMP() {
  SpreadsheetApp.getActiveSheet().appendRow([new Date()]);
}
Prefer 2 changed lines
/** @customfunction */
function STAMP(value) {
  return [[value]];
}
Tip 076 Avoids silent bug MF91003

Do not open UI dialogs or prompts from a custom function

Formula evaluation has no UI session, so SpreadsheetApp.getUi(), Browser.msgBox(), and Browser.inputBox() fail.

Avoid 2 changed lines
/** @customfunction */
function ASK() {
  return Browser.inputBox("Value?");
}
Prefer 2 changed lines
/** @customfunction */
function ASK(value) {
  return value;
}
Tip 077 Avoids silent bug MF91004

Treat custom function arguments as values or 2D arrays, not Range objects

Sheets passes cell values or 2D arrays to custom functions, not Range objects. Calling getValues() on an argument throws a TypeError.

Avoid 1 changed line
/** @customfunction
 * @param {number[][]} input
 */
function SUMALL(input) {
  return input.getValues().flat().reduce((a, b) => a + b, 0);
}
Prefer 1 changed line
/** @customfunction
 * @param {number[][]} input
 */
function SUMALL(input) {
  return input.flat().reduce((a, b) => a + b, 0);
}
Tip 078 Avoids silent bug MF91005

Keep @customfunction formulas synchronous instead of returning Promises

Sheets does not await Promises, so the cell shows #VALUE! or [object Promise].

In myFunction: Remove the async keyword.

Avoid 1 changed line
/** @customfunction */
async function LATER(value) {
  return value;
}
Prefer 1 changed line
/** @customfunction */
function LATER(value) {
  return value;
}
Tip 079 Avoids silent bug MF91006

Do not end a custom function name with an underscore

Names ending in _ are private in Apps Script, so the formula returns #NAME?.

In myFunction: Remove the trailing underscore.

Avoid 1 changed line
/** @customfunction */
function DOUBLE_(value) {
  return value * 2;
}
Prefer 1 changed line
/** @customfunction */
function DOUBLE(value) {
  return value * 2;
}
Tip 080 Avoids silent bug MF91007

Avoid naming custom functions after built-in formulas or cell references

A custom function named SUM or A1 is shadowed by the built-in formula or read as a cell reference.

Avoid 1 changed line
/** @customfunction */
function SUM(value) {
  return value;
}
Prefer 1 changed line
/** @customfunction */
function SUMOF(value) {
  return value;
}
Tip 081 Best practice MF91008

Pass changing inputs to custom functions instead of relying on Date or Math.random()

Sheets caches a custom function's result until its arguments change, so Math.random(), Date.now(), and new Date() do not refresh.

Avoid 2 changed lines
/** @customfunction */
function ROLL() {
  return Math.random();
}
Prefer 2 changed lines
/** @customfunction */
function ROLL(seed) {
  return (seed * 9301 + 49297) % 233280;
}
Tip 082 Best practice MF91009

Keep JSDoc @param tags in sync with custom function parameter names

Sheets builds formula help from @param tags, so a missing or misnamed tag hides the argument help.

In myFunction: Add a placeholder @param tag for each undocumented parameter.

Avoid 1 changed line
/**
 * @customfunction
 * @param {number} amount
 */
function TAX(value) {
  return value * 0.2;
}
Prefer 1 changed line
/**
 * @customfunction
 * @param {number} value
 */
function TAX(value) {
  return value * 0.2;
}
Tip 083 Avoids silent bug MF91010

Declare custom functions as top-level function statements, not arrow functions

Sheets only finds custom functions declared as top-level function statements, not arrow functions or class methods.

In myFunction: Convert the arrow function to a function declaration.

Avoid 1 changed line
/** @customfunction */
const DOUBLE = (value) => value * 2;
Prefer 3 changed lines
/** @customfunction */
function DOUBLE(value) {
  return value * 2;
}
Tip 084 Best practice MF91011

Do not read Session.getActiveUser().getEmail() inside a custom function

A custom function runs without the user's authorization, so Session.getActiveUser().getEmail() returns an empty string and the cell shows a blank result.

Avoid 2 changed lines
/** @customfunction */
function WHOAMI() {
  return Session.getActiveUser().getEmail();
}
Prefer 2 changed lines
/** @customfunction */
function GREETING(email) {
  return "Hello " + email;
}

8 tips

Files and the V8 runtime

Work with Apps Script shared global scope and know which Node or Web globals exist.

Tip 085 Prevents runtime error MF92001

Avoid CommonJS require() in .gs files

Apps Script has no CommonJS module system, so require() throws ReferenceError at runtime.

Avoid 2 changed lines
function parse(text) {
  const yaml = require("yaml");
  return yaml.parse(text);
}
Prefer 1 changed line
function parse(text) {
  return JSON.parse(text);
}
Tip 086 Prevents runtime error MF92002

Omit ES module import and export statements in .gs files

Every .gs file runs as a script in one shared global scope. import and export statements are syntax errors when the project saves.

In myFunction: Remove the export keyword or the export list.

Avoid 1 changed line
export function greet(name) {
  return "Hello " + name;
}
Prefer 1 changed line
function greet(name) {
  return "Hello " + name;
}
Tip 087 Prevents runtime error MF92008

Avoid #private class fields and methods in .gs files

The Apps Script parser rejects private class members such as #count, so saving fails with "ParseError: Unexpected token ILLEGAL" and no file in the project saves.

Avoid 2 changed lines
class Counter {
  #count = 0;
  next() {
    return ++this.#count;
  }
}
Prefer 4 changed lines
class Counter {
  constructor() {
    this._count = 0;
  }
  next() {
    return ++this._count;
  }
}
Tip 088 Avoids silent bug MF92003

Give every top-level function across .gs files a unique name

Files share one global scope, so only the last declaration of a function survives. Which one wins depends on file order.

Avoid 1 changed line
function helper() {
  return 1;
}

function helper() {
  return 2;
}
Prefer 1 changed line
function helper() {
  return 1;
}

function otherHelper() {
  return 2;
}
Tip 089 Prevents runtime error MF92005

Use Apps Script services instead of browser, Node.js, or WHATWG Web globals

Apps Script runs .gs files on Google's servers without browser, Node.js, or WHATWG globals such as window, document, fetch(), process, Buffer, URL, atob(), btoa(), crypto, or structuredClone(). Each throws a ReferenceError. The message names the Apps Script service to use instead.

In myFunction: Replace fetch(), alert(), btoa(), atob(), crypto.randomUUID(), process.env.<KEY>, or structuredClone() with their Apps Script equivalents.

Avoid 1 changed line
function getRates() {
  const response = fetch("https://api.example.com/rates");
  return JSON.parse(response.getContentText());
}
Prefer 1 changed line
function getRates() {
  const response = UrlFetchApp.fetch("https://api.example.com/rates");
  return JSON.parse(response.getContentText());
}
Tip 090 Avoids silent bug MF92006

Run service calls inside functions instead of at file top level

Apps Script runs every file's top-level code before each function call, including simple triggers and custom functions, which cannot use every service. A service call there runs on every execution, and when it fails, every function in the project fails with it.

Avoid 2 changed lines
const sheet = SpreadsheetApp.getActiveSheet();

function addRow(values) {
  sheet.appendRow(values);
}
Prefer 1 changed line
function addRow(values) {
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow(values);
}
Tip 091 Prevents runtime error MF92007

Read const, let, and class bindings from later files inside functions, not at load time

Apps Script loads files in the order the editor lists them. A class, let, or const declared in a later file does not exist yet while an earlier file's top-level code runs, so using it there throws "is not defined". Code inside functions runs later and is fine. The check runs once the editor knows the file order.

Avoid 3 changed lines
const ORDERS_SHEET = CONFIG.sheetName;

function readOrders() {
  return SpreadsheetApp.getActive().getSheetByName(ORDERS_SHEET).getDataRange().getValues();
}
Prefer 1 changed line
function readOrders() {
  return SpreadsheetApp.getActive().getSheetByName(CONFIG.sheetName).getDataRange().getValues();
}
Tip 092 Prevents runtime error MF92009

Avoid top-level await in .gs files

Apps Script .gs files run as classic scripts, not ES modules, so a top-level await fails to save with a SyntaxError. Move await inside an async function, or call synchronous Apps Script APIs directly.

Avoid 1 changed line
const config = await loadConfig();

async function loadConfig() {
  return Promise.resolve({ ready: true });
}
Prefer 8 changed lines
async function main() {
  try {
    const config = await loadConfig();
    Logger.log(config);
  } catch (error) {
    console.error(error);
  }
}

async function loadConfig() {
  return Promise.resolve({ ready: true });
}

14 tips

HTML Service and google.script.run

Bridge client pages and server .gs functions cleanly without XSS or silent nulls.

Tip 093 Prevents runtime error MF97001

Match HtmlService file names exactly, without the .html extension

createHtmlOutputFromFile() and createTemplateFromFile() look up the file by its exact name, without .html. A name that matches no HTML file in the project throws when the line runs. The check runs once the editor knows every file in the project.

In myFunction: Change the name to the closest HTML file in the project.

Avoid 1 changed line
function doGet() {
  return HtmlService.createHtmlOutputFromFile("Pages");
}
Prefer 1 changed line
function doGet() {
  return HtmlService.createHtmlOutputFromFile("Page");
}
Tip 094 Avoids silent bug MF97002

Serve HTML files containing <? ?> scriptlets with createTemplateFromFile().evaluate()

createHtmlOutputFromFile() serves the file as it is, so <? ?> scriptlets in it show on the page as text. A file with scriptlets needs createTemplateFromFile(...).evaluate().

In myFunction: Switch to createTemplateFromFile(...).evaluate().

Avoid 1 changed line
function doGet() {
  return HtmlService.createHtmlOutputFromFile("Page");
}
Prefer 1 changed line
function doGet() {
  return HtmlService.createTemplateFromFile("Page").evaluate();
}
Tip 095 Avoids silent bug Page.html MF97003

Use <?= ?> to escape dynamic values in HTML templates instead of <?!= ?>

<?!= prints a value without escaping it. When the value comes from a user, a sheet, or e.parameter, a visitor can put their own HTML or script on the page. <?= escapes the value; keep <?!= for including another file's HTML.

In myFunction: Print the value escaped with <?=.

Avoid 1 changed line
<p>Hello, <?!= name ?></p>
Prefer 1 changed line
<p>Hello, <?= name ?></p>
Tip 096 Avoids silent bug Page.html MF97004

Print included HTML partials with <?!= include(...) ?>, not <?= ?>

An include() helper returns another file's HTML. Printing it with <?= escapes that HTML, so the page shows the markup as text instead of the styles or script it holds.

In myFunction: Insert the HTML with <?!=.

Avoid 1 changed line
<head><?= include("Styles") ?></head>
Prefer 1 changed line
<head><?!= include("Styles") ?></head>
Tip 097 Prevents runtime error Page.html MF97005

Call only existing public top-level .gs functions through google.script.run

google.script.run can call only top-level functions of the project whose names do not end in an underscore. A typo or a private function fails in the browser with a 'not a function' error. The check runs once the editor knows every file in the project.

In myFunction: Call the closest server function.

Avoid 1 changed line
<script>
  google.script.run.withSuccessHandler(console.log).getRow();
</script>
Prefer 1 changed line
<script>
  google.script.run.withSuccessHandler(console.log).getRows();
</script>
Tip 098 Avoids silent bug MF97006

Convert Date values to ISO strings before returning them to google.script.run

google.script.run passes numbers, strings, booleans, arrays, and plain objects back to the page. A Date is not one of them, so the call fails and the success handler never runs. Return an ISO string or a formatted date instead.

Avoid 1 changed line
function lastRun() {
  return new Date();
}
Prefer 1 changed line
function lastRun() {
  return new Date().toISOString();
}
Tip 099 Avoids silent bug Page.html MF97007

Assign every template property before calling template.evaluate()

Properties read in <?= ?> or <?!= ?> scriptlets must be assigned on the HtmlTemplate instance before calling evaluate(). Reading a property that was never set (or was set on a different template) produces undefined when the page renders.

Avoid 1 changed line
<h1><?= title ?></h1><p><?= username ?></p>
Prefer 1 changed line
<h1><?= title ?></h1>
Tip 100 Best practice Page.html MF97008

Attach .withFailureHandler() to google.script.run calls so errors do not vanish

When a server function throws or hits a quota or permission error, google.script.run drops the error unless .withFailureHandler() is chained on the call.

Avoid 1 changed line
<script>
  google.script.run.withSuccessHandler(console.log).saveRow("Ada");
</script>
Prefer 1 changed line
<script>
  google.script.run.withSuccessHandler(console.log).withFailureHandler(console.error).saveRow("Ada");
</script>
Tip 101 Prevents runtime error Page.html MF97009

Read google.script.run results in .withSuccessHandler(), not as a return value or await

google.script.run invokes server functions asynchronously and always returns undefined, not a value or Promise. Assigning, returning, or awaiting it yields undefined; pass a callback to .withSuccessHandler() instead.

Avoid 3 changed lines
<script>
  async function load() {
    const total = await google.script.run.getTotal();
    console.log(total);
  }
</script>
Prefer 2 changed lines
<script>
  function load() {
    google.script.run.withSuccessHandler(console.log).withFailureHandler(console.error).getTotal();
  }
</script>
Tip 102 Avoids silent bug MF97010

Pass and return only plain JSON-like values or forms across google.script.run

google.script.run serializes only primitives, arrays, plain objects, and <form> elements. Returning Apps Script host objects (such as Range, Sheet, File, or Blob), Map, Set, or RegExp from a server function, or passing a Date or non-<form> DOM node from the page, fails at runtime.

Avoid 1 changed line
function getHeaderRange() {
  return SpreadsheetApp.getActiveSheet().getRange("A1:C1");
}
Prefer 1 changed line
function getHeaderRange() {
  return SpreadsheetApp.getActiveSheet().getRange("A1:C1").getValues();
}
Tip 103 Avoids silent bug Page.html MF97011

Pass the right number of arguments from google.script.run to the server function

When google.script.run calls a known project server function with fewer arguments than required parameters or more arguments than the function accepts, missing arguments arrive as undefined and extra arguments are ignored.

Avoid 1 changed line
<script>
  google.script.run.withFailureHandler(console.error).saveRow("Ada");
</script>
Prefer 1 changed line
<script>
  google.script.run.withFailureHandler(console.error).saveRow("Ada", "ada@example.com");
</script>
Tip 104 Best practice MF97012

Avoid XFrameOptionsMode.ALLOWALL unless the web app must be embedded

setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL) removes X-Frame-Options protection so any third-party site can embed the web app in an iframe. Keep XFrameOptionsMode.DEFAULT unless cross-origin embedding is required.

Avoid 1 changed line
function doGet() {
  return HtmlService.createHtmlOutput("<p>Hello</p>").setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
Prefer 1 changed line
function doGet() {
  return HtmlService.createHtmlOutput("<p>Hello</p>").setXFrameOptionsMode(HtmlService.XFrameOptionsMode.DEFAULT);
}
Tip 105 Avoids silent bug Page.html MF97013

Add target="_blank" to external links and inline sibling assets in HtmlService pages

HtmlService pages run inside a sandboxed iframe and do not serve sibling static files by path. External <a href="https://..."> links need target="_top" or target="_blank" to avoid iframe navigation blocks, and relative <script src>, <link href>, or fetch() paths fail to load.

In myFunction: Add target="_blank" rel="noopener noreferrer" to external links.

Avoid 1 changed line
<a href="https://example.com/docs">Documentation</a>
Prefer 1 changed line
<a href="https://example.com/docs" target="_blank" rel="noopener noreferrer">Documentation</a>
Tip 106 Avoids silent bug MF97014

Render request parameters through HtmlTemplate escaping instead of createHtmlOutput() strings

Concatenating or interpolating e.parameter values or e.postData.contents directly into HtmlService.createHtmlOutput() or .append() renders untrusted input as raw HTML, allowing reflected XSS. Use HtmlService.createTemplate() or createTemplateFromFile() with <?= ?> so Apps Script escapes HTML.

Avoid 1 changed line
function doGet(e) {
  return HtmlService.createHtmlOutput("<p>Hello " + e.parameter.name + "</p>");
}
Prefer 3 changed lines
function doGet(e) {
  const template = HtmlService.createTemplate("<p>Hello <?= name ?></p>");
  template.name = e.parameter.name;
  return template.evaluate();
}

16 tips

Manifest and OAuth scopes

Keep appsscript.json valid, least-privilege, and ready for deployment.

Tip 107 Prevents runtime error MF96010

List every OAuth scope your calls require when setting oauthScopes explicitly

When appsscript.json lists oauthScopes, Apps Script grants only those scopes. A call whose reference page requires a scope missing from the list fails with a permission error at runtime. The check uses the Authorization section of each method's reference page.

In myFunction: Add one of the accepted scopes to oauthScopes in appsscript.json.

Avoid 1 changed line
// appsscript.json: "oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.currentonly"]
function copyTotals() {
  const source = SpreadsheetApp.openById("1AbCdEf");
  return source.getRange("A1").getValue();
}
Prefer 1 changed line
// appsscript.json: "oauthScopes": ["https://www.googleapis.com/auth/spreadsheets"]
function copyTotals() {
  const source = SpreadsheetApp.openById("1AbCdEf");
  return source.getRange("A1").getValue();
}
Tip 108 Best practice appsscript.json MF96011

Remove unused OAuth scopes from appsscript.json to keep consent screens small

Every scope in oauthScopes appears on the consent screen, and sensitive scopes can require app verification. A built-in service scope that no call in the project accepts is likely left over. Projects with libraries, advanced services, or add-on or Chat configuration are skipped, since those can need scopes the code does not show.

In myFunction: Remove the scope from oauthScopes.

Avoid 2 changed lines
{
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets.currentonly",
    "https://www.googleapis.com/auth/drive"
  ]
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets.currentonly"
  ]
}
Tip 109 Avoids silent bug MF96012

Add every fetched URL prefix to urlFetchWhitelist when using an allowlist

When appsscript.json lists urlFetchWhitelist, deployed versions can fetch only URLs under those prefixes. A literal URL passed to UrlFetchApp that no prefix covers fails once the script is deployed.

In myFunction: Add the URL's folder or host to urlFetchWhitelist.

Avoid 1 changed line
// appsscript.json: "urlFetchWhitelist": ["https://api.example.com/v1/"]
function loadRates() {
  return UrlFetchApp.fetch("https://api.example.com/v2/rates").getContentText();
}
Prefer 1 changed line
// appsscript.json: "urlFetchWhitelist": ["https://api.example.com/v2/"]
function loadRates() {
  return UrlFetchApp.fetch("https://api.example.com/v2/rates").getContentText();
}
Tip 110 Avoids silent bug appsscript.json MF96004

Set runtimeVersion to "V8" in appsscript.json

Without runtimeVersion, or with "STABLE" or "DEPRECATED_ES5", Apps Script runs the legacy Rhino runtime, which lacks modern JavaScript such as classes and arrow functions in some contexts. myFunction checks code as V8.

In myFunction: Set runtimeVersion to "V8".

Avoid 0 changed lines
{
  "timeZone": "America/Denver"
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "timeZone": "America/Denver"
}
Tip 111 Prevents runtime error appsscript.json MF96002

Use accepted enum and type values in appsscript.json fields

A manifest field has the wrong JSON type or a value Apps Script does not accept, such as a web app access level, an exceptionLogging setting, a time zone, or an oauthScopes entry that is not a scope URL.

Avoid 1 changed line
{
  "runtimeVersion": "V8",
  "webapp": { "access": "EVERYONE", "executeAs": "USER_DEPLOYING" }
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "webapp": { "access": "ANYONE", "executeAs": "USER_DEPLOYING" }
}
Tip 112 Prevents runtime error appsscript.json MF96005

Include serviceId, userSymbol, and version on every manifest dependency entry

Each entry in dependencies.enabledAdvancedServices needs serviceId, userSymbol, and version, and each library needs libraryId, userSymbol, and version. Two entries cannot share a userSymbol.

Avoid 1 changed line
{
  "runtimeVersion": "V8",
  "dependencies": {
    "enabledAdvancedServices": [{ "serviceId": "drive", "userSymbol": "Drive" }]
  }
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "dependencies": {
    "enabledAdvancedServices": [{ "serviceId": "drive", "userSymbol": "Drive", "version": "v3" }]
  }
}
Tip 113 Prevents runtime error appsscript.json MF96006

Use https:// prefixes with a trailing path in urlFetchWhitelist

Each allowlist prefix must use https://, name a full domain, and have a non-empty path such as a trailing slash. A single * can only stand for the leading subdomain.

Avoid 1 changed line
{
  "runtimeVersion": "V8",
  "urlFetchWhitelist": ["https://api.example.com"]
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "urlFetchWhitelist": ["https://api.example.com/"]
}
Tip 114 Avoids silent bug appsscript.json MF96003

Check top-level appsscript.json field names for typos

appsscript.json accepts a fixed set of top-level fields. A misspelled field, such as oauthScope for oauthScopes, has no effect.

In myFunction: Rename the field to the manifest field it most likely means.

Avoid 1 changed line
{
  "runtimeVersion": "V8",
  "oauthScope": ["https://www.googleapis.com/auth/spreadsheets"]
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/spreadsheets"]
}
Tip 115 Prevents runtime error appsscript.json MF96001

Keep appsscript.json strict JSON with no comments or trailing commas

The Apps Script editor will not save a project whose appsscript.json does not parse. Trailing commas and comments are the usual causes.

Avoid 1 changed line
{
  "runtimeVersion": "V8",
  "timeZone": "America/Denver",
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "timeZone": "America/Denver"
}
Tip 116 Best practice MF96013

Use MailApp.sendEmail() instead of GmailApp when you only send mail

GmailApp needs the scope to read, send, and delete all of a user's mail. When a project only sends mail with GmailApp.sendEmail() and uses no from address, MailApp.sendEmail() takes the same arguments and asks only to send mail as the user.

In myFunction: Send with MailApp.

Avoid 1 changed line
function notify(to) {
  GmailApp.sendEmail(to, "Report ready", "The weekly report is in the shared folder.");
}
Prefer 1 changed line
function notify(to) {
  MailApp.sendEmail(to, "Report ready", "The weekly report is in the shared folder.");
}
Tip 117 Best practice appsscript.json MF96014

Request the narrowest OAuth scope your code needs, such as .readonly or .currentonly

When every call that relies on a listed scope also accepts a narrower one, such as drive.readonly instead of drive, listing the narrower scope gives the script less access and shows users a smaller request. Projects with libraries, advanced services, or add-on configuration are skipped.

In myFunction: Replace the scope with the narrower one.

Avoid 1 changed line
{
  "oauthScopes": ["https://www.googleapis.com/auth/drive"]
}
Prefer 1 changed line
{
  "oauthScopes": ["https://www.googleapis.com/auth/drive.readonly"]
}
Tip 118 Prevents runtime error appsscript.json MF96015

Run ANYONE_ANONYMOUS web apps as USER_DEPLOYING, not USER_ACCESSING

A web app that executes as the user accessing it needs a signed-in user to run as, so it cannot allow anonymous access. Deploy it to execute as you, or require visitors to sign in.

In myFunction: Run the web app as you, or require sign-in.

Avoid 1 changed line
{
  "webapp": { "access": "ANYONE_ANONYMOUS", "executeAs": "USER_ACCESSING" }
}
Prefer 1 changed line
{
  "webapp": { "access": "ANYONE_ANONYMOUS", "executeAs": "USER_DEPLOYING" }
}
Tip 119 Prevents runtime error MF96016

Enable Advanced Services in appsscript.json before calling Drive, Sheets, or Gmail

Advanced services such as Drive, Sheets, or Gmail exist only after you add them under Services, which lists them in dependencies.enabledAdvancedServices. Until then, code that uses one throws "is not defined". The check runs when the editor can read appsscript.json.

In myFunction: Add the service to dependencies.enabledAdvancedServices in appsscript.json.

Avoid 1 changed line
// appsscript.json lists no advanced services
function listFiles() {
  return Drive.Files.list({ pageSize: 10 });
}
Prefer 1 changed line
// appsscript.json: { "userSymbol": "Drive", "version": "v3", "serviceId": "drive" }
function listFiles() {
  return Drive.Files.list({ pageSize: 10 });
}
Tip 120 Prevents runtime error MF96017

Add third-party libraries like OAuth2 under Libraries before referencing them

Code that calls OAuth2, OAuth1, Cheerio, FirebaseApp, or BetterLog expects the open-source library by that identifier. Until the library is added under Libraries, the identifier is not defined. The check runs when the editor can read appsscript.json.

Avoid 1 changed line
// appsscript.json lists no libraries
function getService() {
  return OAuth2.createService("github");
}
Prefer 1 changed line
// appsscript.json lists the OAuth2 library
function getService() {
  return OAuth2.createService("github");
}
Tip 121 Avoids silent bug appsscript.json MF96018

Turn off developmentMode on libraries before deploying a project

A library entry with "developmentMode": true runs the library's HEAD code rather than a pinned version, which breaks at runtime for any user who does not have edit access to the library project.

In myFunction: Set developmentMode to false.

Avoid 1 changed line
{
  "runtimeVersion": "V8",
  "dependencies": {
    "libraries": [
      { "libraryId": "1abc", "userSymbol": "MyLib", "version": "1", "developmentMode": true }
    ]
  }
}
Prefer 1 changed line
{
  "runtimeVersion": "V8",
  "dependencies": {
    "libraries": [
      { "libraryId": "1abc", "userSymbol": "MyLib", "version": "1", "developmentMode": false }
    ]
  }
}
Tip 122 Avoids silent bug MF96019

Keep @OnlyCurrentDoc capitalized and consistent with your calls and oauthScopes

/** @OnlyCurrentDoc */ limits container-bound document access to the active file (*.currentonly), so openById() and openByUrl() fail at runtime unless explicit oauthScopes are listed. When appsscript.json defines oauthScopes, Apps Script silently ignores @OnlyCurrentDoc. Apps Script's parser is also case-sensitive and ignores miscased tags such as @onlyCurrentDoc.

In myFunction: Fix miscased @onlyCurrentDoc capitalization to @OnlyCurrentDoc.

Avoid 2 changed lines
/** @OnlyCurrentDoc */
function readOther(id) {
  return SpreadsheetApp.openById(id).getName();
}
Prefer 2 changed lines
/** @OnlyCurrentDoc */
function readActive() {
  return SpreadsheetApp.getActiveSpreadsheet().getName();
}

3 tips

Type checking and JSDoc

Keep type checking accurate across JSON payloads, event handlers, and JSDoc.

Tip 123 Best practice MF90005

Double-check arguments on uncurated Apps Script methods against the reference

Some Apps Script methods have no verified parameter list yet. myFunction marks the call so you check the reference before adding arguments.

In myFunction: Guidance to check the Apps Script reference before adding arguments.

Avoid 2 changed lines
function clientAction() {
  return AddOnsResponseService.newGmailClientAction();
}
Prefer 2 changed lines
function message() {
  return AddOnsResponseService.newChatMessage();
}
Tip 124 Best practice MF90006

Annotate JSON.parse() and untyped variables with JSDoc @type to keep checking active

A declaration or return value typed as any turns off checking for every use of it. Adding a JSDoc type restores completions and diagnostics.

Avoid 0 changed lines
function readConfig(text) {
  const config = JSON.parse(text);
  return config.name;
}
Prefer 2 changed lines
/** @param {string} text */
function readConfig(text) {
  /** @type {{ name: string }} */
  const config = JSON.parse(text);
  return config.name;
}
Tip 125 Avoids silent bug MF90007

Use myFunction global JSDoc types like Events.DoPost instead of GoogleAppsScript.*

JSDoc annotations such as GoogleAppsScript.Events.DoPost or GoogleAppsScript.Spreadsheet.Range come from DefinitelyTyped's @types/google-apps-script package. Replacing them with myFunction's global types (Events.DoPost, SpreadsheetApp.Range) uses the runtime-verified declarations directly.

In myFunction: Replace the GoogleAppsScript.* type with the matching global Apps Script type.

Avoid 1 changed line
/** @param {GoogleAppsScript.Events.DoPost} e */
function doPost(e) {
  return ContentService.createTextOutput(e.postData.contents);
}
Prefer 1 changed line
/** @param {Events.DoPost} e */
function doPost(e) {
  return ContentService.createTextOutput(e.postData.contents);
}

Catch them while you type

Let the editor check all 125 tips for you.

Install the free myFunction Chrome extension to run these checks directly inside the Apps Script editor, with one-click quick fixes where available.