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.
Google Scripts Lessons 1-10
Click on a lesson below for a written tutorial demonstrating the lesson.
- Lesson 1 – “Hello World!”
- Lesson 2 – Challenge: Calling Functions
- Lesson 3 – Variables
- Lesson 4 – Variable Passing
- Lesson 5 – Variable Passing Challenge
- Lesson 6 – Arrays of Variables
- Lesson 7 – Modifying a Google Doc
- Lesson 8 – Modify Doc and Send Email
- Lesson 9 – Simple Feedback script
- Lesson 10 – Full-scale feedback