In the last article, we started a discourse on what Google Apps Script meant and how it could be integrated into our various Google workspaces. This article will build a structure from the foundation that has been laid by our previous article. Today, we will
be learning how to write basic logic using JavaScript fundamentals inside Apps Script while trying to automate with Google Forms and Gmail.
Functions, the building blocks for Apps Script.
As stated in the first tutorial, Functions are reusable blocks of code that help perform a specific task. They help organize your code by making it easier to read and preventing any forms of redundancy.
Functions should describe what they do. For example, if you want a function that sends an email, you could call it sendEmail
.
This is a perfect example of a function that greets users
function greetUser() {
Logger.log("Hello from Apps Script!");
}
Variables – Storing and Using Data
Think of variables like a container that stores values. Variables let you store texts, numbers, and lists.
For example
let name = "John";
const age = 30;
var message = "Welcome!";
If we add this with the function we had written before
function showUserInfo() {
let name = "Alice";
const country = "Nigeria";
Logger.log("Name: " + name);
Logger.log("Country: " + country);
}
Logic - Making Decisions based on the if/else
conditions
At its core, programming is about instructing a computer to perform tasks. A significant part of this involves making decisions. if/else
statements are the foundational building blocks for introducing logic and decision-making into your code.
if
statement: This allows a block of code to be executed only if a specified condition is true.
if (temperature > 25) {
print("It's hot outside!")
}
else
statement: This provides an alternative block of code to be executed if the if condition (and any subsequent else if conditions) is false.
if (isRaining) {
wearRaincoat()
} else {
wearLightJacket()
}
Understanding the switch-case
Statement
Imagine you have to write multiple conditions for a complex task. It’s not considered good practice to use numerous if-else statements. In such cases, a switch-case statement is a better and more organized alternative.
The switch-case statement is another control flow mechanism used for decision-making, offering an alternative to long chains of if-else if-else statements, especially when you are checking a single variable against multiple possible constant values.
How it Works:
The switch
statement evaluates an expression once. The value of the expression is then compared with the values of each case label.
If a match is found, the code block associated with that case is executed.
The break
keyword (usually used at the end of each case block) is crucial. It terminates the switch statement once a match is found and its code is executed, preventing "fall-through" to subsequent case blocks.
The default
keyword is optional and acts like an else clause. If no case matches the expression's value, the code block under default is executed.
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// ... more cases
default:
// code to execute if no case matches
break;
}
Loops – Repeating Tasks
Use loops to repeat actions multiple times (e.g., send multiple emails, or check multiple rows in a sheet).
We have for
loops
for (let i = 0; i < 5; i++) {
Logger.log("Step " + i);
}
We have forEach which is commonly used for arrays
let fruits = ["apple", "banana", "orange"];
fruits.forEach(function(fruit) {
Logger.log(fruit);
});
If we put all we have been learning together, we would have something like this
function checkUsers() {
let users = ["John", "Mary", "Sam"];
for (let i = 0; i < users.length; i++) {
if (users[i] === "Mary") {
Logger.log(users[i] + " is the admin.");
} else {
Logger.log("Hello, " + users[i]);
}
}
}
Having laid this background, let's automate real tasks while using Google Forms to send emails on each trigger
Automating Tasks with Google Forms + Apps Script
To make this blog easier to follow, I would break each point into different steps
Create a form on forms.google.com
Add fields like
Name
,Email
, andMessage
In the Form editor, click Responses > Link to Sheets
Choose “Create new spreadsheet”
Click Extensions > Apps Script
Paste this code:
function sendEmailOnFormSubmit(e) {
const responses = e.values; // All answers in order
const name = responses[1]; // First question
const email = responses[2]; // Second question
const message = responses[3]; // Third question
const subject = `Hello ${name}, we got your message!`;
const body = `Hi ${name},\n\nThanks for contacting us.\n\nYou said: "${message}"\n\nWe'll reply soon!\n\nRegards,\nYour Team`;
MailApp.sendEmail(email, subject, body);
}
Let me break this down for you:
-
function sendEmailOnFormSubmit(e) {
This defines a function named sendEmailOnFormSubmit.
It takes one parameter: e (short for event object).
The e object
is automatically passed to the function when it’s triggered by a form submission. It contains information about the submitted form response.
2.
const responses = e.values;
e.values
is an array of all the responses from the submitted form. Each item corresponds to each response based on the order to which they appear in the form
3.
const name = responses[1];
const email = responses[2];
const message = responses[3];
Extracts specific values from the responses array. Make sure your form fields are in this exact order, or adjust the indices accordingly.
4.
MailApp.sendEmail(email, subject, body);
This sends an email using Apps Script’s built-in MailApp service with the given subject and body.
Back to our discourse
In the script editor, click the clock icon (Triggers) on the left.
Click “+ Add Trigger”
Choose function: sendEmailOnFormSubmit
Event type: From spreadsheet
Trigger type: On form submit
Click Save and authorize the script (you’ll be prompted)
Submit a response in your Google Form
Check the email inbox you entered — you’ll receive a custom email
Note on Permissions
The first time you run or trigger a script, you’ll need to authorize it. Apps Script will ask for permissions like: View and manage spreadsheets
, Send email on your behalf
It's time to go😔😟🥺
I hope you were also able to follow along and practice. In our next tutorial, we will be learning how to do some complex tasks with Google Drive and Docs using Google Apps Script
See you next time!
Top comments (0)