toString() method

The toString() method in Apps Script is used to convert a value to a string. It is often used when a value needs to be represented as a string, such as when working with user interface elements or when building strings for output.

One example use case for toString() is when working with dates. Apps Script represents dates as JavaScript Date objects, which can be converted to strings using the toString() method. For example, you can use toString() to format a date as a string in a specific format, such as “MM/dd/yyyy”.

Another example use case for toString() is when working with arrays. If you want to convert an array to a string, you can use the toString() method to join the elements of the array into a single string separated by commas. For example, if you have an array of city names, you can use toString() to create a comma-separated list of cities.

Here’s an example of using toString() with dates:

function formatDate(date) {
  return date.toString().split(' ').slice(1, 4).join(' ');
}

var today = new Date();
Logger.log('Today is ' + formatDate(today));

This code uses toString() to format today’s date as a string in the format “Mon Jan 01 2022”, and then uses split(), slice(), and join() to extract only the month, day, and year.

And here’s an example of using toString() with arrays:

function formatCities(cities) {
  return cities.toString();
}

var myCities = ['New York', 'Los Angeles', 'Chicago'];
Logger.log('My cities are ' + formatCities(myCities));

This code uses toString() to join the elements of myCities into a single string separated by commas. The resulting string is “New York,Los Angeles,Chicago”.