Web App Development with Google Apps Script/syntax

ajax
Ajax stands for "Asynchronous JavaScript and XML" and it's the ability for a web page to communicate with a server without reloading the page.

To do it in you use the   tool. This command, which has several varieties, runs JavaScript code on Google's servers and potentially returns information back to your web page.

For example, if you wanted to send a name to a server, then check if it's in your spreadsheet and return true if it is and false if it's not that you can set to a variable, you'd do this:

First the server side code:

Now the portion of "main.html" with the JavaScript you'd be doing

The flow is: main javascript -> function on server -> returns data to your SuccessHandler -> your successHandler does something.

Array numbering
A simple (and quite forgivable) mistake is to be off by a row or column when moving data back and forth between google sheets and javascript is the array numbering issuer. Javascript starts numbering at zero while google sheets starts numbering at 1. Here's an example:

filter
If you need to filter an array, use, um, :

As with find, forEach, and map you can also use the index if you want:

find
If you need to find an element in an array,  is super helpful:

forEach
If you need to loop through an array and do something with every element, you could of course do this:

But you could also do this, which I think reads better:

Note that you never have to initialize the "i" variable this way.

If you need to access the item (fruit) and the location (index) that it's in the array: Note the parentheses around  that makes that magic work. Also note that you still don't have to declare the i variable!

includes
If you're looking to see if an array includes a particular element, try :

map
Similar to forEach,  is a great way to create a new array based on an existing array. Let's say you wanted to add a tag around some text in an array:

You can also have easy access to the index of the item in the array:

sort
Sorting arrays is quite valuable and sometimes a pain. Assume you have a 2D array from a spreadsheet with columns of "name", "age", "email". If you want to sort them by age, do this:

really sort needs to return a true or false when determining who should go first, but by subtracting two numbers, if you get a zero or a negative number it'll be treated as false whereas a positive number will be treated as true.

If you wanted to sort by the age and the name (alphabetically) you could: