How do loops work in Google Sheets Apps Script?

Loops in Apps Script let you repeat code over rows, columns, sheets, or API pages. You read ranges into arrays with getValues(), process each item in a for or forEach loop, then write results back in one setValues() call when possible. Batch reads and writes beat cell-by-cell updates for speed and quota limits.

When to use it

Use loops when you need to scan many rows, clean data, build summaries, or call an API for each record. Pair loops with arrays from getValues() for reports, deduplication, and row-by-row rules that formulas cannot express cleanly.

When to skip it

Skip loops when a single QUERY, MAP, or ARRAYFORMULA can do the job in the sheet without script. Avoid looping every cell on large tabs without batching; execution time and UrlFetch quotas add up fast.

How it works

  1. 1

    Open Extensions > Apps Script and define a function that gets the target range with getRange().

  2. 2

    Call getValues() once to load data into a two-dimensional JavaScript array.

  3. 3

    Use for (let i = 0; i < rows.length; i++) or rows.forEach() to read each row and build an output array.

  4. 4

    {:"Apply your logic inside the loop"=>"trim text, compute totals, skip blanks, or collect matches."}

  5. 5

    Write the output array back with setValues() in one range update instead of many setValue() calls.

  6. 6

    Test on a small sample range first, then add Logger.log counts and guard rails for empty data.

Examples in Google Sheets

Flag overdue rows

Loop column B dates against today in a script function. Write "Overdue" to column E only when the date is past and status in column D is not "Paid".

Deduplicate by email

Read column A into an array, track seen emails in a Set, and write "Duplicate" in column B for second and later occurrences.

Paginate an API

Use a while loop with a page token from UrlFetchApp until no next page remains, pushing each record into a master array before flushing to the sheet.

Build this without starting from a blank cell

Use a Better Sheets tool for Apps Script loops, then watch a walkthrough when you want the full pattern.

Better Sheets resources

Common mistakes

  • Calling getValue() or setValue() inside a tight loop on thousands of rows, which is slow and brittle.
  • Forgetting that getValues() row and column indexes start at 0 while sheet rows start at 1.
  • Infinite while loops when a break condition never becomes true after an API change.
  • Mutating the sheet range you are iterating without recalculating bounds, causing skipped rows.
  • Running long loops from onEdit instead of a menu action or time-driven trigger.

Frequently asked questions

for vs forEach in Apps Script?
Both work on arrays from getValues(). Classic for loops give you the index; forEach is readable when you do not need the row number for writing back.
Can I loop all sheets in a file?
Yes. Use SpreadsheetApp.getActive().getSheets() and loop each sheet name or tab object.
How do I avoid the six-minute timeout?
Process in chunks, store the last processed row in PropertiesService, and resume on the next run.
Should loops replace QUERY?
Prefer QUERY or formulas when the logic is tabular and stable. Use loops for custom steps formulas cannot do.
Can loops call external APIs?
Yes with UrlFetchApp, but respect daily quotas and add delays or batch endpoints when available.
Do loops work with onEdit?
They can, but keep onEdit loops tiny. Heavy loops belong in manual functions or scheduled triggers.
How do I debug a loop?
Logger.log the index and a sample row inside the loop, then check Executions after a test run.
Can I break out of a loop early?
Use break in a for loop or return from the function when you found what you need.

Related Tutorials

Watch how Apps Script loops works

Browse more tutorials
Two Things to Know When Starting to Learn Google Sheets

Two Things to Know When Starting to Learn Google Sheets

Two things I would teach every beginner to immediately improve your skil...
10 Google Sheets I Wish Someone Would Make

10 Google Sheets I Wish Someone Would Make

if you're looking for ideas on what sheets to make I think this video is...
Iterate Numbers with a Simple Apps Script

Iterate Numbers with a Simple Apps Script

You're joining a company and they have some Google Sheets already create...
Curate Google Sheets Easily - Automatic Bookmarklet Maker

Curate Google Sheets Easily - Automatic Bookmarklet Maker

Curated sites, articles, and more web resources super easily into a Goog...
Now Do It Every Damn Day - Learn to Code in Google Sheets Part 5

Now Do It Every Damn Day - Learn to Code in Google Sheets Part 5

Now that we have a script that we wanna run every day, how do we run thi...
From Sheet to Script And Back Again - Learn to Code In Google Sheets Part 3

From Sheet to Script And Back Again - Learn to Code In Google Sheets Part 3

In this video, I'm going to share with you how to go basically from shee...

Related blog posts

Guides that explain Apps Script loops in more depth.

Browse the blog

Related glossary terms

Done reading about Apps Script loops?

Membership unlocks 636+ tutorials, unlimited generators, and every template. Practical lessons. Zero fluff.

Need this once

Jump to a free tool or a single tutorial for this topic.

Learning Sheets for real

Unlock the full library, generators, and templates with membership.