Google Script Lesson 4 – Variable Passing

In the previous example, there was a bit of code that was repeated twice: the Logger.log series of commands. Whenever you see code being used more than once, it’s a good sign that you need to build a new function for it. However, in order for this to work in this case you need to ‘pass’ your new function the necessary variables: x, y, and z.This is where the parentheses () coming after the function are important. When you CALL a function, you are passing a set of values, separated by commas, to the function. These are called parameters. When you DEFINE a function, you create new, local variables that receive those values (in the same order as the function call).Take a look at the example below, or click here to see the Script file.

function myFunction() {
var x = "This variable contains a string.";
var y = 3;
var z = 3.14;

logVariables(x, y, z);

x = x + 1;
y = y + 1;
z = z + 1;

logVariables(x, y, z);
logVariables(typeof x,typeof y,typeof z);
}

function logVariables(x, y, z) {
Logger.log(x);
Logger.log(y);
Logger.log(z);
Logger.log("");
}

 

Note: this program does exactly the same thing as the previous example. The difference is that the code here is much ‘cleaner’, meaning that there is nothing that is redundant or unnecessary.

Leave a comment

Your email address will not be published. Required fields are marked *