Google Script Lesson 6 – Arrays of Variables

In Google Script, as in most coding, arrays are an important way of storing a series of variables. For a look at arrays in javascript, click here: http://www.w3schools.com/js/js_arrays.asp

Take a look at the following example, or click here to make your own copy of the code:

function myFunction() {
  var data = ["johnnysmith@school.edu","Johnny is doing well in school."]
  
  var studentEmail = data[0];
  var message = data[1];
  
  emailStudent(studentEmail, message);
}

In this example, notice that we declare the variable ‘data’ as an array by using the square brackets [], along with variable values separated by commas.

Notice that when using an array, you can specify which element of the array you want to use by using a number in the square brackets, for example [0]. In coding, the most common way of counting is to start with 0, so 0 is the first element in the array. It takes a while to get used to counting from zero, but it’s fun when you get used to it.

Here’s the second half of the program: the emailStudent function.

function emailStudent(studentEmail, message) {
  var timeStamp = new Date();
  
  // Construct message
  message = timeStamp + "\nHere is your feedback:\n" + message + "\n\nRegards, \nMr Jones\n";
  
  Logger.log(studentEmail);
  Logger.log(message);
}

In the function emailStudent, we see two variables passed into it as parameters, studentEmail and message. A third variable is declared there, timeStamp. It’s value, new Date(), is what’s called an object, but don’t worry too much about what objects are right now.

In the message construction part, you see an example of adding strings together to make a longer message. In this case, we are adding the timeStamp to the message, along with some context for it. The \n code means ‘new line’ in HTML.

Challenge

Try modifying the messages, either in the data array or in the message construction

Leave a comment

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