Google Script Lesson 3 – Variables

In this example we begin to look at variables. Just like in algebra, a variable can hold a range of values, but in coding they are also a little bit different. Variables in JavaScript have different types, the most basic of which are Strings and Numbers. Simply put, Strings contain text and Numbers contain numerical values.

var x = "This variable contains a string.";
var y = 3;
var z = 3.14;

When you first introduce a variable, you put ‘var’ in front of it so that it is clear what it is. Note that by using variables, you can use Logger.log without putting the value itself between the parentheses.

Logger.log(x);
Logger.log(y);
Logger.log(z);

Note you can also modify variables. This part is quite different from math, because mathematically y = y + 1 makes no sense. However, in coding this simply means SET the value of y to whatever the current value of y is, plus 1.

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

In the case of ‘x’, it is a string, so it simply adds the string of ‘1’ to the end of the initial string. This is a way you can build up larger and larger string into messages, which can later be added to documents or emailed

Test out this example by clicking this link or on “03 – Variables Example to the right”. Then make a copy and click Run > myFunction. Click View > Logs and see what results were recorded. Any surprises?

Note that adding 1 to 3.14 give a bit of a strange result. Don’t worry about this too much, but for now just know that when you add integers to integers, it works fine. When you add integers to numbers with decimals, it can get just a little bit off.

Finally, you need to understand that all of these variables are what are called LOCAL variables. This means that, outside of the function in which they are declared, they have no meaning. It is a good practice for now to make all of your variables local, because otherwise you will build bad habits. By having your variables expire outside of each function, it prevents them from interfering with variables in other functions.  With very small programs this is not a big deal, but as programs gain in complexity, it is very important to self-contain each function so that you don’t have to worry about all of your variables interfering with one another.

Leave a comment

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