2. Apps Script and JavaScript
Module 1 · 15 minutes · Lessons 1–1 as needed; read the related service introduction first
Open Interactive LessonDiscover
How can apps script and javascript solve a real automation problem without hiding an incorrect result?
- Explain the input, important operations and evidence boundary in apps script and javascript
- A rectangular range can contain several cells; one scalar value is written to every cell.
- Predict a changed or invalid input, repair the source and verify the actual result
Predict
Which values or resources will change, and which should stay unchanged? Write your prediction before execution.
Understand
Automation repeats a defined rule on data. A reliable rule names its input, validates assumptions, changes only intended records and gives evidence of its effect. A computer does not infer that Pending means Complete. Writing B2:B4 changes three status cells in one explicit operation. The before-and-after view lets you verify both affected and unaffected cells.
Real-world application
Use this technique in a reviewed spreadsheet workflow. A rectangular range can contain several cells; one scalar value is written to every cell. Apply it first to a copy containing fictional records; only a separately authorized Google deployment changes real Workspace data.
Definitions
- Apps Script and JavaScript
- Automation repeats a defined rule on data. A reliable rule names its input, validates assumptions, changes only intended records and gives evidence of its effect.
- Virtual service adapter
- A supported local implementation of selected service methods operating on fictional JSON state; it is not a live Google account connection.
- Verification contract
- An independently inspected expected console/resource result under declared fixture inputs.
Local execution boundary: the browser changes fictional state only. Google authorization and deployment happen separately.
Exact controls and expected results
- Run in Virtual Workspace
- Execute the visible source against the current fictional records. Expected: A rectangular range can contain several cells; one scalar value is written to every cell.
- Run on fresh sample
- Restore the sample input, then execute the visible source. Expected: {"logs":[],"error":null,"resource":"sheets","value":{"People":[["Name","Status"],["Alex","Ready"],["Jordan","Ready"],["Morgan","Ready"]],"Sales":[["Customer","Amount","Approved"],["Alex",120,true],["Jordan",80,false],["Morgan",200,true]],"Tasks":[["Task","Status"],["Review invoice","Open"],["Publish report","Complete"]]}}
- Execution Trace
- Inspect ordered supported method calls, arguments and actual recorded results. Expected: The trace reflects this run; replay is not a paused Google debugger.
- Reset Example
- Confirm replacement to restore source and sample state. Expected: Your current modifications are replaced with the prepared case.
Example 1: Working apps script and javascript
A rectangular range can contain several cells; one scalar value is written to every cell.
function main() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}Important line explanations
- Line 1: function main() {
- Define a named callable block; defining it does not invoke it.
- Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 3: sheet.getRange("B2:B4").setValue("Ready");
- Select the addressed range and write this scalar value into its cells. This chained statement changes state; inspect the target and preserved neighboring cells.
- Line 4: }
- Close the current block; indentation shows the scope.
Exact expected output and resource
{
"logs": [],
"error": null,
"resource": "sheets",
"value": {
"People": [
[
"Name",
"Status"
],
[
"Alex",
"Ready"
],
[
"Jordan",
"Ready"
],
[
"Morgan",
"Ready"
]
],
"Sales": [
[
"Customer",
"Amount",
"Approved"
],
[
"Alex",
120,
true
],
[
"Jordan",
80,
false
],
[
"Morgan",
200,
true
]
],
"Tasks": [
[
"Task",
"Status"
],
[
"Review invoice",
"Open"
],
[
"Publish report",
"Complete"
]
]
}
}Example 2: Find the first incorrect operation
This deliberately changed operation uses "A2:A4". Predict the mismatch and compare its actual output with the reference.
function main() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("A2:A4").setValue("Ready");
}Important line explanations
- Line 1: function main() {
- Define a named callable block; defining it does not invoke it.
- Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 3: sheet.getRange("A2:A4").setValue("Ready");
- Select the addressed range and write this scalar value into its cells. This chained statement changes state; inspect the target and preserved neighboring cells.
- Line 4: }
- Close the current block; indentation shows the scope.
Exact expected output and resource
{
"logs": [],
"error": null,
"resource": "sheets",
"value": {
"People": [
[
"Name",
"Status"
],
[
"Ready",
"Pending"
],
[
"Ready",
"Pending"
],
[
"Ready",
"Pending"
]
],
"Sales": [
[
"Customer",
"Amount",
"Approved"
],
[
"Alex",
120,
true
],
[
"Jordan",
80,
false
],
[
"Morgan",
200,
true
]
],
"Tasks": [
[
"Task",
"Status"
],
[
"Review invoice",
"Open"
],
[
"Publish report",
"Complete"
]
]
}
}Example 3: Repeat the operation and inspect idempotency
Execute the same operation twice against retained fictional state. Explain whether it repeats reads, duplicates a created object or safely skips completed work. The trace records actual supported service calls.
function lessonAction() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}
function main() {
lessonAction();
lessonAction();
}Important line explanations
- Line 1: function lessonAction() {
- Define a named callable block; defining it does not invoke it.
- Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 3: sheet.getRange("B2:B4").setValue("Ready");
- Select the addressed range and write this scalar value into its cells. This chained statement changes state; inspect the target and preserved neighboring cells.
- Line 4: }
- Close the current block; indentation shows the scope.
- Line 5: function main() {
- Define a named callable block; defining it does not invoke it.
- Line 6: lessonAction();
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 7: lessonAction();
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 8: }
- Close the current block; indentation shows the scope.
Exact expected output and resource
{
"logs": [],
"error": null,
"resource": "sheets",
"value": {
"People": [
[
"Name",
"Status"
],
[
"Alex",
"Ready"
],
[
"Jordan",
"Ready"
],
[
"Morgan",
"Ready"
]
],
"Sales": [
[
"Customer",
"Amount",
"Approved"
],
[
"Alex",
120,
true
],
[
"Jordan",
80,
false
],
[
"Morgan",
200,
true
]
],
"Tasks": [
[
"Task",
"Status"
],
[
"Review invoice",
"Open"
],
[
"Publish report",
"Complete"
]
]
}
}Example 4: Add a diagnostic failure boundary
Separate entry, success and a rethrown failure. A failure marker must not masquerade as success and must not swallow the original error.
function lessonAction() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}
function main() {
console.log("Start: Apps Script and JavaScript");
try { lessonAction(); console.log("Completed operation"); }
catch(error) { console.error("Failed operation: " + error.message); throw error; }
}Important line explanations
- Line 1: function lessonAction() {
- Define a named callable block; defining it does not invoke it.
- Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 3: sheet.getRange("B2:B4").setValue("Ready");
- Select the addressed range and write this scalar value into its cells. This chained statement changes state; inspect the target and preserved neighboring cells.
- Line 4: }
- Close the current block; indentation shows the scope.
- Line 5: function main() {
- Define a named callable block; defining it does not invoke it.
- Line 6: console.log("Start: Apps Script and JavaScript");
- Record this actual result; inspect side effects too rather than treating a log as success.
- Line 7: try { lessonAction(); console.log("Completed operation"); }
- Record this actual result; inspect side effects too rather than treating a log as success.
- Line 8: catch(error) { console.error("Failed operation: " + error.message); throw error; }
- Record this actual result; inspect side effects too rather than treating a log as success.
- Line 9: }
- Close the current block; indentation shows the scope.
Exact expected output and resource
{
"logs": [
"Start: Apps Script and JavaScript",
"Completed operation"
],
"error": null,
"resource": "sheets",
"value": {
"People": [
[
"Name",
"Status"
],
[
"Alex",
"Ready"
],
[
"Jordan",
"Ready"
],
[
"Morgan",
"Ready"
]
],
"Sales": [
[
"Customer",
"Amount",
"Approved"
],
[
"Alex",
120,
true
],
[
"Jordan",
80,
false
],
[
"Morgan",
200,
true
]
],
"Tasks": [
[
"Task",
"Status"
],
[
"Review invoice",
"Open"
],
[
"Publish report",
"Complete"
]
]
}
}Example 5: Executable service-call and result assertions
Inject recording service adapters that delegate to the same supported virtual operations. Compare actual arguments and logs with fixed authored expectations. Change the operation and verify that the assertion fails; this local contract does not certify Google integration.
function invokeLesson(e, SpreadsheetApp, DocumentApp, DriveApp, GmailApp, MailApp, FormApp, CalendarApp, SlidesApp, ScriptApp, PropertiesService, CacheService, LockService, HtmlService, UrlFetchApp, Utilities, console, Logger) {
function lessonAction() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}
return lessonAction(e);
}
// A local dependency-injection contract test: calls still delegate to supported adapters.
function main() {
const records = [];
function serializable(value) {
try { return JSON.parse(JSON.stringify(value)); } catch (error) { return "[non-serializable]"; }
}
function recordService(target, path) {
return new Proxy(target, {get(object, key) {
const value = object[key];
if (typeof value !== "function") return value;
return (...args) => {
const method = path + "." + String(key);
records.push({method, args: args.map(serializable)});
const result = value.apply(object, args);
if (Array.isArray(result)) return result.map((item, index) => item && typeof item === "object" && !Array.isArray(item) ? recordService(item, method + "()[" + index + "]") : item);
return result && typeof result === "object" && !Array.isArray(result) && !(result instanceof Date) ? recordService(result, method + "()") : result;
};
}});
}
function recordLog(...args) {
records.push({log: args.map(value => typeof value === "string" ? value : JSON.stringify(value)).join(" ")});
}
const capturedConsole = {log: recordLog, error: recordLog, warn: recordLog, info: recordLog};
invokeLesson(e, recordService(SpreadsheetApp, "SpreadsheetApp"), recordService(DocumentApp, "DocumentApp"), recordService(DriveApp, "DriveApp"), recordService(GmailApp, "GmailApp"), recordService(MailApp, "MailApp"), recordService(FormApp, "FormApp"), recordService(CalendarApp, "CalendarApp"), recordService(SlidesApp, "SlidesApp"), recordService(ScriptApp, "ScriptApp"), recordService(PropertiesService, "PropertiesService"), recordService(CacheService, "CacheService"), recordService(LockService, "LockService"), recordService(HtmlService, "HtmlService"), recordService(UrlFetchApp, "UrlFetchApp"), recordService(Utilities, "Utilities"), capturedConsole, capturedConsole);
const expected = [
{
"method": "SpreadsheetApp.getActiveSpreadsheet",
"args": []
},
{
"method": "SpreadsheetApp.getActiveSpreadsheet().getActiveSheet",
"args": []
},
{
"method": "SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange",
"args": [
"B2:B4"
]
},
{
"method": "SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange().setValue",
"args": [
"Ready"
]
}
];
if (JSON.stringify(records) !== JSON.stringify(expected)) throw new Error("Contract mismatch: inspect actual calls and logs");
console.log("Contract assertions passed: lesson 2");
}Important line explanations
- Line 1: function invokeLesson(e, SpreadsheetApp, DocumentApp, DriveApp, GmailApp, MailApp, FormApp, CalendarApp, SlidesApp, ScriptApp, PropertiesService, CacheService, LockService, HtmlService, UrlFetchApp, Utilities, console, Logger) {
- Inject the recording adapters and console into the lesson function, including its helpers; preserve the main entry point.
- Line 2: function lessonAction() {
- Define a named callable block; defining it does not invoke it.
- Line 3: const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 4: sheet.getRange("B2:B4").setValue("Ready");
- Select the addressed range and write this scalar value into its cells. This chained statement changes state; inspect the target and preserved neighboring cells.
- Line 5: }
- Close the current block; indentation shows the scope.
- Line 6: return lessonAction(e);
- Return a result or stop this branch; returning differs from logging.
- Line 7: }
- Close the current block; indentation shows the scope.
- Line 8:
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 9: // A local dependency-injection contract test: calls still delegate to supported adapters.
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 10: function main() {
- Define a named callable block; defining it does not invoke it.
- Line 11: const records = [];
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 12: function serializable(value) {
- Define a named callable block; defining it does not invoke it.
- Line 13: try { return JSON.parse(JSON.stringify(value)); } catch (error) { return "[non-serializable]"; }
- Parse syntax before validating business fields; malformed JSON throws.
- Line 14: }
- Close the current block; indentation shows the scope.
- Line 15: function recordService(target, path) {
- Define a named callable block; defining it does not invoke it.
- Line 16: return new Proxy(target, {get(object, key) {
- Intercept supported service method access for this local contract test; calls still delegate to the original fictional adapter.
- Line 17: const value = object[key];
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 18: if (typeof value !== "function") return value;
- Evaluate this condition and test both accepted and rejected branches.
- Line 19: return (...args) => {
- Return a result or stop this branch; returning differs from logging.
- Line 20: const method = path + "." + String(key);
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 21: records.push({method, args: args.map(serializable)});
- Capture an actual method argument or console value for comparison with the frozen authored contract.
- Line 22: const result = value.apply(object, args);
- Execute the actual supported adapter method with its original receiver and arguments; the recorder does not fabricate a successful result.
- Line 23: if (Array.isArray(result)) return result.map((item, index) => item && typeof item === "object" && !Array.isArray(item) ? recordService(item, method + "()[" + index + "]") : item);
- Build a new output item for every input item, preserving the intended row shape.
- Line 24: return result && typeof result === "object" && !Array.isArray(result) && !(result instanceof Date) ? recordService(result, method + "()") : result;
- Return a result or stop this branch; returning differs from logging.
- Line 25: };
- Close the current block; indentation shows the scope.
- Line 26: }});
- Close the current block; indentation shows the scope.
- Line 27: }
- Close the current block; indentation shows the scope.
- Line 28: function recordLog(...args) {
- Define a named callable block; defining it does not invoke it.
- Line 29: records.push({log: args.map(value => typeof value === "string" ? value : JSON.stringify(value)).join(" ")});
- Capture an actual method argument or console value for comparison with the frozen authored contract.
- Line 30: }
- Close the current block; indentation shows the scope.
- Line 31: const capturedConsole = {log: recordLog, error: recordLog, warn: recordLog, info: recordLog};
- Bind the named value for the operations below; referenced arrays and objects may still be mutable.
- Line 32: invokeLesson(e, recordService(SpreadsheetApp, "SpreadsheetApp"), recordService(DocumentApp, "DocumentApp"), recordService(DriveApp, "DriveApp"), recordService(GmailApp, "GmailApp"), recordService(MailApp, "MailApp"), recordService(FormApp, "FormApp"), recordService(CalendarApp, "CalendarApp"), recordService(SlidesApp, "SlidesApp"), recordService(ScriptApp, "ScriptApp"), recordService(PropertiesService, "PropertiesService"), recordService(CacheService, "CacheService"), recordService(LockService, "LockService"), recordService(HtmlService, "HtmlService"), recordService(UrlFetchApp, "UrlFetchApp"), recordService(Utilities, "Utilities"), capturedConsole, capturedConsole);
- Inject the recording adapters and console into the lesson function, including its helpers; preserve the main entry point.
- Line 33: const expected = [
- These are fixed authored expectations. They are not recalculated from the learner’s changed source.
- Line 34: {
- Close the current block; indentation shows the scope.
- Line 35: "method": "SpreadsheetApp.getActiveSpreadsheet",
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 36: "args": []
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 37: },
- Close the current block; indentation shows the scope.
- Line 38: {
- Close the current block; indentation shows the scope.
- Line 39: "method": "SpreadsheetApp.getActiveSpreadsheet().getActiveSheet",
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 40: "args": []
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 41: },
- Close the current block; indentation shows the scope.
- Line 42: {
- Close the current block; indentation shows the scope.
- Line 43: "method": "SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange",
- Resolve a one-based rectangular cell selection; this alone does not write data.
- Line 44: "args": [
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 45: "B2:B4"
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 46: ]
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 47: },
- Close the current block; indentation shows the scope.
- Line 48: {
- Close the current block; indentation shows the scope.
- Line 49: "method": "SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange().setValue",
- Resolve a one-based rectangular cell selection; this alone does not write data.
- Line 50: "args": [
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 51: "Ready"
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 52: ]
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 53: }
- Close the current block; indentation shows the scope.
- Line 54: ];
- Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
- Line 55: if (JSON.stringify(records) !== JSON.stringify(expected)) throw new Error("Contract mismatch: inspect actual calls and logs");
- Reject any changed call or result. This deterministic fixture comparison is not a general semantic-equivalence or Google integration test.
- Line 56: console.log("Contract assertions passed: lesson 2");
- Record this actual result; inspect side effects too rather than treating a log as success.
- Line 57: }
- Close the current block; indentation shows the scope.
Exact expected output and resource
{
"logs": [
"Contract assertions passed: lesson 2"
],
"error": null,
"resource": "sheets",
"value": {
"People": [
[
"Name",
"Status"
],
[
"Alex",
"Ready"
],
[
"Jordan",
"Ready"
],
[
"Morgan",
"Ready"
]
],
"Sales": [
[
"Customer",
"Amount",
"Approved"
],
[
"Alex",
120,
true
],
[
"Jordan",
80,
false
],
[
"Morgan",
200,
true
]
],
"Tasks": [
[
"Task",
"Status"
],
[
"Review invoice",
"Open"
],
[
"Publish report",
"Complete"
]
]
}
}Build and test
Repair the supplied source so that A rectangular range can contain several cells; one scalar value is written to every cell. Inspect the output and preserve unrelated data. A completion message alone does not satisfy the resource contract.
function main() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("A2:A4").setValue("Ready");
}Graduated hints
Hint 1
Locate "A2:A4" in the failing source and predict its effect before changing it.
Hint 2
Compare the intended operation "B2:B4" with the failing operation "A2:A4". Use the earliest different log or state value.
Hint 3
Replace the relevant "A2:A4" operation with "B2:B4"; rerun on fresh sample and explain why the result now satisfies the contract.
Reference solution
function main() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}Explain and reflect
Explain why A rectangular range can contain several cells; one scalar value is written to every cell. Which operation provides the strongest evidence? Propose one independent input with an exact expected outcome, and state what must still be checked on Google.
Extend this operation for a second realistic dataset. Preserve the source records, define a normal and invalid case before execution, and write a rerun policy for side effects. Review the resulting source with a peer before authorizing real services.
Troubleshooting
Choose main as the entry function, or use the exact entry required by the example. Use the Manual event for this example. If there is no console output inspect the sheets preview and Execution Trace. Reset before comparing to the fixed sample contract. Unsupported Google methods fail visibly; inspect the supported-service reference rather than assuming a successful fixture is a Google integration test.
Knowledge check
Explain the key method or operator. Give an exact output for a second input, plus one invalid case. Verify the result in the interactive lesson; written explanations need self or educator review.
Optional AI practice
Explain this concept using the source above. Help implement one small extension and define its tests. Review/debug the source using its actual expected output; cite real method references and never claim execution.
Transfer to Google and authorization guide
Next lesson: Understanding the script editor
Common mistakes
- Confusing "B2:B4" with "A2:A4".
- Running again on changed state and expecting the original fixture result.
- Treating fictional service execution as proof of permissions, quotas or live API behavior.
Official references
Three lesson-specific AI prompts
Explain
Explain this Apps Script lesson: Apps Script and JavaScript. Objective: Explain the input, important operations and evidence boundary in apps script and javascript. Current reference source:
function main() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}
Expected: A rectangular range can contain several cells; one scalar value is written to every cell.
My changed source: [paste the current visible source]. Actual output/error: [paste the run result]. Explain supported methods, types, authorization, duplicate behavior and verification boundaries. Give normal, boundary and invalid tests. Do not claim you executed Google services; do not request credentials. I will verify every proposed change.Implement
Implement this Apps Script lesson: Apps Script and JavaScript. Objective: Explain the input, important operations and evidence boundary in apps script and javascript. Current reference source:
function main() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}
Expected: A rectangular range can contain several cells; one scalar value is written to every cell.
My changed source: [paste the current visible source]. Actual output/error: [paste the run result]. Explain supported methods, types, authorization, duplicate behavior and verification boundaries. Give normal, boundary and invalid tests. Do not claim you executed Google services; do not request credentials. I will verify every proposed change.Review/debug
Review/debug this Apps Script lesson: Apps Script and JavaScript. Objective: Explain the input, important operations and evidence boundary in apps script and javascript. Current reference source:
function main() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange("B2:B4").setValue("Ready");
}
Expected: A rectangular range can contain several cells; one scalar value is written to every cell.
My changed source: [paste the current visible source]. Actual output/error: [paste the run result]. Explain supported methods, types, authorization, duplicate behavior and verification boundaries. Give normal, boundary and invalid tests. Do not claim you executed Google services; do not request credentials. I will verify every proposed change.