Welcome back. In Part 1, we have seen how we were able to create a custom function to convert USD to SGD just by writing a few lines of codes in Google Apps Script.
We will be going through those 3 lines of codes to understand more about the USDTOSGD function. Before that, let’s get familiar with the Google Apps Script Interface.
Go ahead and click on the “Run” button. You will see two lines in the Execution log. If you are seeing a different interface from here, not to worry. This is because you could be still using the legacy editor.
What is a function?
A function is a set of statements that performs a task or calculates a value. It usually takes in some input and returns an output. In this USDTOSGD function, it takes in a numeric value (USD), performs some calculations, and returns another numeric value (SGD). More about this function later.
You can have multiple functions under a script project. In other words, a script project represents a collection of files and resources in Google Apps Script. A script project can have more than one script files (with a .gs extension). or multiple HTML files (a .html
extension).
To help you understand the concept of functions better, here’s how it looks like visually.
We created a Bound script earlier, meaning the codes we have written in Google Apps Script were bounded to the Google Sheet which we started with. This explains why we can invoke the function from the Google Sheet itself.
In this case, the function USDTOSGD can be called from the Google Sheet by simply typing
=USDTOSGD(A2)
In order for the function to return the SGD value, we need to tell the function the value in USD. Hence, we included A2 in the formula. A2 is the cell which contains the value ($245) to be converted. This is known as passing a parameter to a function.
If the function works correctly, it will return the SGD value to the Google Sheet after performing the calculations.
Not all functions require a parameter to be provided as an input. And not all functions have to be invoked from a Google Sheet. Functions can also be called from another function.
If you are confused by now, fear not. We will go one step at a time.