Beginner guide to coding with Google Apps Script

Introduction to Google Apps Script

What is Google Apps Script or G.A.S.?

It’s a cloud based scripting language for extending the functionality of Google Apps and building lightweight web-based applications.

What does this mean in practice: It’s a coding language where you can write small programs performing custom behaviors that go beyond the standard features of Google Apps. The code is stored and executed on Google’s servers.

It means you can do cool stuff like automating repetitive tasks, creating, modifying and emailing documents to people, and linking up your Google Sheets to other data sources. Heck, you can even build complex web forms, use a Google Sheet as your database, programatically create charts and publish it all to the web. In other words, you can build fully featured, lightweight web applications.

Writing your first Google Apps Script

So let’s go ahead and write our first, extremely basic program, the classic “Hello world” program beloved of computer teaching departments the world over.

We’re going to write a script that is bound to our Google Sheet, or you might say contained within our Google Sheet. This is known in the jargon as a container-bound script.

Begin by creating a new Google Sheet. Then, click the menu Tools > Script editor... to open a new tab with the code editor window:

script editor menu

This will open a new tab in your browser, which is the Google Apps Script editor window:

GAS editor window

By default, it’ll open with a single Google Script file ( and a default code block, myFunction():

In the code window, between the curly braces after the function myFunction() syntax, write the following line of code so you have this in your code window:

Your code window should now look like this:

GAS first function

Next hit the run button (the black triangle), which prompts you to authorize the app to run, as shown in the following image:

GAS Authorization

Clicking Continue pops up another window in turn, showing what permissions your app needs to run. In this instance the app wants to view and manage your spreadsheets in Google Drive, so click Allow (otherwise your script won’t be able to interact with your spreadsheet or do anything):

GAS Authorization

Next, GAS will show you two status messages to tell you what’s happening.

First this one:

GAS execute script

And then this one:

GAS execute status 2

If anything goes wrong with your code, this is stage when you’d see a warning message (instead of the yellow message, you’ll get a red box with an error message in it).

Now, assuming you got those two yellow status messages and they’ve both automatically disappeared from view, then your program has run successfully. Click back on the browser tab with your spreadsheet (most likely the tab to the left of the one we’re in).

You should see the output of your program, a message box popup with the classic “Hello world!” message:

GAS output hello world

Click on Ok to dismiss.

Great job! You’ve now written your first apps script program.


Before we continue, let’s rename our function to something more meaningful. At present, it’s called myFunction which is the default, generic name generated by Google. Every time I want to call this function (i.e. run it to do something) I would write myFunction(). This isn’t very descriptive, so let’s rename it to helloWorld(), which gives us some context.

So change your code in line 1 from this:

to this:

Note, it’s convention in Apps Script to use the CamelCase naming convention, starting with a lowercase letter. Hence, we name our function helloWorld, with a lowercase h at the start of hello and an uppercase W at the start of World.

Adding a custom menu

In its current form, our program is pretty useless for many reasons, not least because we can only run it from the script editor window and not from our spreadsheet. So let’s fix that by adding a custom menu to the menu bar of our spreadsheet, so that a user can run the script within the spreadsheet without needing to open up the editor window.

This is actually surprisingly easy to do, requiring only a few lines of code. Add the following 6 lines of code into the editor window, above the helloWorld() function we created above, as shown here:

If you look back at your spreadsheet tab in the browser now, nothing will have changed. You won’t have the custom menu there yet. We need to re-open our spreadsheet (refresh it) or run our onOpen() script first, for the menu to show up.

To run onOpen() from the editor window, first select the onOpen function as shown in this image:

Add custom menu

Once you’ve selected the onOpen function, the small triangle button will change from light gray to black, meaning it can be clicked to run your chosen function:

Run function

Now, when you return to your spreadsheet you’ll see a new menu on the right side of the Help option, called My Custom Menu. Click on it and it’ll open up to show a choice to run your Hello World program:

Custom menu

More Google Apps Script examples

Custom function/maps example

Let’s create a custom function with Apps Script, and also demonstrate the use of the Maps Service. We’ll be creating a small custom function that calculates the driving distance between two points, based on Google Maps Service driving estimates.

The goal is to be able to have two place-names in our spreadsheet, and type the new function in a new cell to get the distance, as follows:

GAS custom function for maps

The solution should be:

GAS custom map function  output

Copy the following code into the Apps Script editor window and save. First time, you’ll need to run the script once from the editor window and click “Allow” to ensure the script can interact with your spreadsheet.

Saving social media data

Let’s take a look at another simple use case.

Here, I’ve setup an importxml function to extract the number of followers a specific social media channel has (e.g. in this case a Reddit channel), and I want to save copy of that number at periodic intervals, like so:

save data in google sheet

In this script, I’ve created a custom menu (as we did above) to run my main function. The main function, saveData(), copies the top row of my spreadsheet (the live data) and pastes it to the next blank line below my current data range as text, thereby “saving” a snapshot in time.

The code for this example is:

See here for a full step-by-step guide to creating and running this script.

Google Apps Script example in Google Docs

GAS is by no means confined to Sheets only, and is equally applicable in the Docs environment. Here’s a quick example of a script that inserts a specific symbol or text string into your Doc wherever your cursor is:

Google Docs Apps Script

We do this using Google App Scripts as follows:

1. Create a new Google Doc

2. Open script editor from the menu: Tools > Script editor...

3. Click on: Create script for > Blank Project

Apps script menu

4. In the newly opened Script tab, remove all of the boilerplate code (the myFunction code block)

5. Copy in the following code:

6. You can change the special character in this line

var element = cursor.insertText('§§');

to whatever you want it to be, e.g.

var element = cursor.insertText('( ͡° ͜ʖ ͡°)');

7. Click Save and give your script project a name (doesn’t affect the running so call it what you want e.g. Insert Symbol)

8. Run the script for the first time by clicking on the menu: Run > onOpen

9. Google will recognize the script is not yet authorized and ask you if you want to continue. Click Continue

10. Since this the first run of the script, Google Docs asks you to authorize the script (I called my script “test” which you can see below):

Docs Apps Script Auth

11. Click Allow

12. Return to your Google Doc now.

13. You’ll have a new menu option, so click on it:
My Custom Menu > Insert Symbol

14. Click on Insert Symbol and you should see the symbol inserted wherever your cursor is.

Use the Logger class

Use the Logger class to output text messages to the log files, to help debug code.

The log files can be accessed after the program has finished running, by going to View > Show Logs (or Cmd + Enter, or Ctrl + Enter (on PC)).

The syntax in its most basic form is Logger.log(something in here). This records the value(s) of variable(s) at different steps of your program.

For example, add this script to a code file your editor window:

Run the script in the editor window, then View > Show Logs and you should see:

logger output

Real world examples from my own work

I’ve only scratched the surface of the outermost epidermis, not even millimeters deep, of what’s possible using GAS to extend the Google Apps experience.

Here’s a couple of interesting projects I’m working on:

1) A Sheets/web-app consisting of a custom web form that feeds data into a Google Sheet (including uploading images to Drive and showing thumbnails in the spreadsheet), then creates a PDF copy of the data in the spreadsheet and automatically emails it to the users. And with all the data in a master Google Sheet, it’s possible to perform data analysis, build dashboards showing data in real-time and share/collaborate with other users.

2) A dashboard that connects to a Google Analytics account, pulls in social media data, checks the website status and emails the user if it goes down, and emails a summary screenshot as a PDF at the end of each day.

Web dashboard

3) A marking template that can send scores/feedback to students with a single click from within Google Sheets. Check out the how-to post I wrote.

Send data from Google Sheets to Slack

Further Resources

Imagination and patience to learn are the only limits to what you can do and where you can go with GAS. I hope you feel inspired to try extending your Sheets and Docs and automate those boring, repetitive tasks!

For further reading, I’ve created this list of resources for information and inspiration:

Apps Script References

Start writing more advanced scripts with the official Apps Script starter guide – a more advanced Hello World program!

Official Google Documentation

Google Apps Developer Blog

Google Apps Script for Developers Training Video Course from O’Reilly

Collection of great blog posts relating to GAS

Integrating Google Apps Script with Slack

Using Google Sheets and GAS as a backend database

Alexa rank checker with email notifications in Google sheets

How to Create Custom Functions in Google Sheets

List of some popular Apps Script projects


Google Docs Help Forum

Google Apps Script G+ community

Desktop Liberation Apps Script community from Bruce Mcpherson

Stack Overflow GAS questions

Google Apps Script Experts

Zig Mandel (GDE)

Bruce Mcpherson (GDE)

Antonio Guzmán Fernández (GDE)

Martin Hawksey (GDE)

Ivan Kutil (GDE)

Romain Vialard (GDE)

James Ferreira (GDE)

Andrew Stillman (GDE)

Andrew Roberts

Amit Agarwal

GDE – Google Developer Experts are experts in their chosen fields (in this case GAS) and recognized by Google for their outstanding contributions. More info here.

Books and other miscellaneous tips

Going GAS book

Going GAS by Bruce Mcpherson is a newly published (i.e. bang up-to-date as of April 2016) book covering the entire GAS ecosystem, with a specific focus on making the transition from Office/VBA into Google Apps/GAS. Even if you don’t use Office or VBA much or at all, it’s still a very useful resource. It’s been a few years since I’ve done any serious VBA work, but I still found the book very helpful and a great overview of the GAS environment.

learning gas book

Learning Google Apps Script by Ramalingam Ganapathy is another brand new Google Apps Script book, intended for learning Apps Script. I haven’t used this particular book.

Google Sheets Programming With Google Apps Script by Michael Maguire is an ebook available through leanpub. I haven’t used this particular book.

I believe other Google Sheets books are older and therefore may advocate deprecated code or not follow current best practices. Caveat emptor!

Finally, if you do get into GAS and start writing lots of code, try out this color editor for your Apps Script window. It’ll change the default white screen to a dark screen with better highlight and folder options for your projects. This setup is much more akin to other professional code editors like Sublime Text.

5 thoughts on “Beginner guide to coding with Google Apps Script”

  1. Hi, Im writing some code in google script, but when I open de file, my script doesn’t work until the first minute i Think, its like there is a delay before the script really respond to my calls on buttons, do you know why is this happening?

    1. Hi Armando,

      Hmm, there shouldn’t be any substantial delay, certainly not a minute. The script could be affected by your internet connection speed, but I wouldn’t expect to see such a big delay, especially if other web services load normally.

      Inefficient code, i.e. lots of calls to/from the Google Sheets or other Google services, can make a script run slowly, so it’s best practice to minimize the number of calls required. More reading here at the official Apps Script docs:

      I suggest sharing your question/code on the Apps Script forum here: where there’s a community of experts who can suggest specific fixes.

      Hope that helps.


  2. hi, i want to track a user who copy, cut, or delete the more then 10 cells at once, please provide me a code or a way how can i do it

Leave a Reply

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