Why Best Practices Matter in Apps Script
Apps Script projects often start as quick automations but grow into critical business tools relied on by entire teams. Code written without structure becomes impossible to maintain, debug, or hand off to someone else. Following best practices from the start saves significant pain down the road.
1. Batch Your Read and Write Operations
This is the single most impactful performance optimization in Apps Script. Every call to the Spreadsheet, Gmail, Drive, or Calendar services involves a round-trip to Google's servers. Minimizing those calls is essential.
❌ Slow — cell-by-cell writing:
for (let i = 0; i < 100; i++) {
sheet.getRange(i + 1, 1).setValue(data[i]); // 100 server calls!
}
✅ Fast — batch write:
const values = data.map(item => [item]);
sheet.getRange(1, 1, values.length, 1).setValues(values); // 1 server call
2. Use the Properties Service for Configuration
Never hard-code API keys, email addresses, or environment-specific values inside your functions. Store them in the Properties Service instead:
// Store a value (run once)
PropertiesService.getScriptProperties().setProperty("ADMIN_EMAIL", "admin@example.com");
// Retrieve it in your code
const adminEmail = PropertiesService.getScriptProperties().getProperty("ADMIN_EMAIL");
This keeps sensitive data out of your code and makes it easy to update configuration without editing the script itself.
3. Always Add Error Handling
Automated scripts run unattended — when they fail silently, you won't know until something goes wrong in production. Wrap critical operations in try/catch blocks:
function safeEmailSend(recipient, subject, body) {
try {
GmailApp.sendEmail(recipient, subject, body);
Logger.log(`Email sent to ${recipient}`);
} catch (error) {
Logger.log(`Failed to send email: ${error.message}`);
// Optionally notify yourself about the failure
GmailApp.sendEmail(Session.getActiveUser().getEmail(),
"Script Error Alert", error.message);
}
}
4. Name Your Functions and Variables Clearly
Apps Script projects often outlive their original author. Write code that explains itself:
- Use descriptive function names:
sendMonthlyInvoiceReminders()notdoThing() - Use
camelCasefor variables,UPPER_SNAKE_CASEfor constants - Add a brief comment above any non-obvious logic
- Group related functions together in the file
5. Use const and let Instead of var
Apps Script fully supports modern JavaScript (ES6+). Use const for values that won't change and let for those that will. Avoid var entirely — its function-scoped behavior causes subtle bugs.
6. Break Large Functions Into Smaller Ones
A function should do one thing well. If your function is longer than 40–50 lines, it's doing too much. Extract logical chunks into helper functions:
// Instead of one massive function:
function processMonthlyReport() {
const data = fetchSheetData();
const summary = calculateSummary(data);
const doc = createReportDocument(summary);
sendReportByEmail(doc);
}
This makes each piece individually testable and far easier to debug.
7. Manage Execution Time Proactively
Scripts have a 6-minute execution limit. For long-running tasks (processing thousands of rows), design your script to work in batches and use the Properties Service to track progress across runs:
function processInBatches() {
const props = PropertiesService.getScriptProperties();
let startRow = parseInt(props.getProperty("lastProcessedRow") || "1");
const batchSize = 200;
// Process batch, then save progress
props.setProperty("lastProcessedRow", String(startRow + batchSize));
}
8. Log Meaningful Information
Use Logger.log() or console.log() generously during development, and keep key operational logs in production. The Stackdriver logging panel (View → Logs / Executions) is your primary debugging tool — make it useful.
Summary Checklist
- ☑ Batch all Spreadsheet reads and writes
- ☑ Store config in Properties Service
- ☑ Wrap critical code in try/catch
- ☑ Use clear, descriptive names
- ☑ Use
const/let, notvar - ☑ Keep functions small and focused
- ☑ Handle the 6-minute execution limit
- ☑ Log meaningful information