JavaScript covers the core fundamentals of Google Apps Script, existing as the coding language that adds both automation and functionality to Google Workspace. In this blog, let us discuss the primary principles of JavaScript you need to be aware of for writing effective Apps Script code
Understanding the Role of JavaScript in Apps Script
Apps Script uses JavaScript with a few key differences from the browser-based version you might know. Think of it as JavaScript's responsible older sibling – it runs on Google's servers rather than in your browser, and it's tailored specifically for Google Workspace integration.
When you write Apps Script code, you're essentially writing JavaScript that can directly interact with Google services. It essentially implies that you can modify spreadsheets, create documents, send emails, and handle calendars with only a few lines of program.
For example, this simple JavaScript function in Apps Script can create a new Google Doc:
function createNewDoc() {
DocumentApp.create('My New Document');
}
Variables, Data Types, and Operators
Variables are the building blocks for storing data in JavaScript. They are declared using keywords such as var, let, or const. Here’s an example:
let username = "John"; // A string variable
const age = 25; // A constant integer
Data Types include:
- String: Textual data (e.g., "Hello World")
- Number: Numerical values (e.g., 10, 3.14)
- Boolean: Logical values (true or false)
- Array: A collection of items (e.g., [1, 2, 3])
- Object: A collection of key-value pairs (e.g., {name: "John", age: 25})
Operators; Allow you to perform operations on variables and values:
Arithmetic Operators: +, -, *, /
let sum = 5 + 3; // Addition
let difference = 10 - 4; // Subtraction
let product = 6 * 2; // Multiplication
let quotient = 15 / 3; // Division
Comparison Operators: ==, !=, >, <
- Equal to (==): Checks if two values are equal.
- Not equal to (!=): Checks if two values are not equal.
- Strict equal to (===): Checks if two values are equal and of the same type.
- Greater than (>): Checks if the left value is greater than the right value.
- Less than (<): Checks if the left value is less than the right value.
Logical Operators: &&, ||
let andResult = true && false; // Logical AND
let orResult = true || false; // Logical OR
Control Structures: Loops and Conditional Statements
Control structures help manage the flow of execution in your script. The most common ones include:
Conditional Statements
Conditional statements in JavaScript allow your program to make decisions based on certain conditions. This means that your code can execute different blocks of code depending on whether specific conditions are true or false. Let’s explore how to use if, else, and else if statements with examples.
1. Using if Statement
The if statement is used to specify a block of code that will run only if a specified condition is true.
Syntax:
if (condition) {
// Block of code to be executed if the condition is true
}
Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
Explanation:
- In this example, we check if age is greater than or equal to 18.
- Since the condition is true, it prints "You are an adult."
2. Using else Statement
The else statement allows you to specify a block of code that will run if the condition in the if statement is false.
Syntax:
if (condition) {
// Block of code to be executed if the condition is true
} else {
// Block of code to be executed if the condition is false
}
Example:
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are not an adult yet.");
}
Explanation:
- Here, we check if age is greater than or equal to 18.
- Since the condition is false, it prints "You are not an adult yet."
3. Using else if Statement
The else if statement allows you to test another condition if the first condition is false. You can have multiple else if statements for different conditions.
Syntax:
if (condition1) {
// Block of code to be executed if condition1 is true
} else if (condition2) {
// Block of code to be executed if condition1 is false and condition2 is true
} else {
// Block of code to be executed if both conditions are false
}
Example:
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: D or below");
}
Explanation:
In this example, we check the value of the score.
The first condition checks if the score is 90 or above. If true, it prints "Grade: A."
If the first condition is false, it checks if the score is 80 or above for "Grade: B."
If that’s also false, it checks for scores of 70 or above for "Grade: C."
If none of these conditions are met, it prints "Grade: D or below."
Fig: Working of Conditional Statements
Loops in Google Apps Script:
Loops are important tools in programming that let you repeat a block of code multiple times. In Google Apps Script, which is based on JavaScript, you can use loops to automate tasks, especially when working with data in Google Sheets. Let us take a closer look at different kinds of looping constructs and explore them with the help of a few examples.
Types of Loops
- For Loop
- While Loop
- Do While Loop
1. For Loop
The for loop is used when you know exactly how many times you want to repeat something.
Syntax:
for (initialization; condition; increment) {
// Code to be executed
}
Example:
Here’s a simple example of a for loop that prints numbers from 1 to 5:
function logNumbers() {
for (let i = 1; i <= 5; i++) {
Logger.log("Number: " + i);
}
}
Explanation:
- The loop starts with i set to 1.
- It keeps going as long as i is less than or equal to 5.
- After each time it runs, i goes up by 1.
- This will print the numbers 1 through 5.
2. While Loop
The while loop runs as long as a certain condition is true. It checks the condition before running the code inside the loop.
Syntax:
while (condition) {
// Code to be executed
}
Example:
Here’s an example of a while loop that prints numbers from 1 to 5:
function logNumbersWhile() {
let i = 1;
while (i <= 5) {
Logger.log("Number: " + i);
i++;
}
}
Explanation:
- The variable i starts at 1.
- The loop runs as long as i is less than or equal to 5.
- Inside the loop, it prints the current value of i and then adds 1 to it.
- This will also print the numbers 1 through 5.
3. Do While Loop
The do while loop is similar to the while loop, but it always runs the code inside at least once before checking the condition.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
Here’s an example of a do while loop that prints numbers from 1 to 5:
function logNumbersDoWhile() {
let i = 1;
do {
Logger.log("Number: " + i);
i++;
} while (i <= 5);
}
Explanation:
- The variable i starts at 1.
- The code inside the do block runs first, printing the current value of i.
- After running that code, it checks if i is less than or equal to 5.
- This will also print the numbers 1 through 5.
Fig: Working of Looping Statements
Functions in Google Apps Script: Definition, Parameters, and Return Values
Functions are an important part of programming that help you organize your code. They allow you to group a set of instructions that you can use multiple times throughout your program. Let us go deep into functions and learn what they are, how they work, and explore some simple examples.
What is a Function?
A function is typically a block of program that executes a particular task in the code. You can take an analogy of recipe to understand function well: once you get the recipe (the function), you can apply it whenever and wherever you like without having to re-write the code from scratch.
Key Parts of a Function
- Definition: This is where you create the function and tell it what to do.
- Parameters: These are the inputs you can give to the function. Parameters enable programmers to pass key data into the function.
- Return Value: This is the output that the function gives back after it finishes its task.
How to Define a Function
Here’s how you define a function in Google Apps Script:
function functionName(parameter1, parameter2) {
// Code to be executed
return result; // Optional return value
}
Example of a Function
Let’s create a simple function that adds two numbers together.
Step 1: Define the Function
function addNumbers(a, b) {
let sum = a + b; // Add the two numbers
return sum; // Return the result
}
Explanation:
- The function is named addNumbers.
- It takes two parameters, a and b, which are the numbers we want to add.
- Inside the function, we calculate the sum of a and b.
- Finally, we return the result (the sum).
Step 2: Call the Function
Now, let’s use this function in another part of our code:
function main() {
let result = addNumbers(5, 10); // Call the function with 5 and 10
Logger.log("The sum is: " + result); // Log the result
}
Explanation:
- We created another function called main.
- Inside main, we call addNumbers with the numbers 5 and 10.
- The result (15) is stored in the variable result.
- Finally, we log the message "The sum is: 15" to the console.
Final Thought
JavaScript in Apps Script provides numerous opportunities for ensuring high automation and improving your tasks with Google Workspace. While the web developers might be familiar with code or syntax, the true potential exists in how Apps Script upgrade capabilities of JavaScript to perform interaction with Google’s services.
As you create projects with Apps Script, keep in mind that clean and well-defined code is not just limited to good practice– it's all about creating sustainable solutions that can improve with your requirements. You can start small, extensively test the code, and slowly expand your script as your familiarity with JavaScript and AppsScript increases. The time you spend learning the fundamentals will surely help you in the long run. If your basics are strong, you can easily learn advanced concepts and create efficient and powerful platforms that can revolutionize your workflow.