Skip to content

Instantly share code, notes, and snippets.

@derekmartinla
Created September 6, 2016 17:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save derekmartinla/0cdc19c5bdd805583fe64cfd48289f2d to your computer and use it in GitHub Desktop.
Save derekmartinla/0cdc19c5bdd805583fe64cfd48289f2d to your computer and use it in GitHub Desktop.

Chapter 2 - The Absolute Minimum JavaScript You Need To Know

Introduction

This chapter introduces the JavaScript language in the most efficient way possible. We'll explore the basics of JavaScript syntax, statements, variables, data structures, data types, functions, decision logic, regular expressions, and finish the tour by introducing the JavaScript Object.

Ground Rules

It's important to note that the goal of this chapter is not to make you an expert in JavaScript (or JS for short). Such a goal would be unbecoming of a language that is as rich and complex as JavaScript. Rather, the goal is to give you just enough knowledge so that you can painlessly follow the rest of the book. Below are several great books for those who would like to grow their JavaScript knowledge:

Reminder: Don't expect to become a JavaScript expert at the end of this chapter!

Basic syntax

JavaScript Comments

Let's start our journey learning how to write comments in JavaScript. But before we do, a quick aside on what how our code actually runs.

Key Point: JavaScript is an interpreted language, meaning that any code that we write will be read in, translated into instructions that a computer can understand, and then executed (i.e. the computer will then do what we told it to do).

Most of the content of your AdWords Scripts will, unshockingly, be instructions that the computer will perform on your behalf. But we also can add comments to our code -- these are portions of the script that the JavaScript intepreter will consciously ignore. Comments allow us to both document our code and stub out any code that we would like to keep from running.

Comments come in two two flavors:

// This is  single-line JavaScript comment. If you want to comment beyond one line,
// you need to use another '//'

/* 
  Behold, I am multi-line JavaScript comment.
  You can write whatever you want between the /* and */ and 
  the JavaScript  interpreter will ignore it. 
*/ 

You should always comment your code. This lets other people understand what your trying to accomplish and will also remind you what you were trying to accomplish in a script whenever you review it after the fact.

Pro Tip: Plan out your scripts by writing the logic down in JS comments.

Statements

In programming parlance, a statement is the smallest standalone element that expressses some action to be carried out[^4]. (https://en.wikipedia.org/wiki/Statement_(computer_science))

Despite the wordiness, the idea behind statements are straight-forward. Think of them in the same way that we commonly think of sentences.

Example: Jack is 160 lbs.

var jack = 160;

Example: Greg is two years younger than Erin.

var greg = erin - 2;

Example: In order to convert kilometers to miles, multiply the # of kilometers by 0.621371.

var k = 100;
var miles = k * 0.621371; // 62.1371

Pro Tip: A code block is set of one or more statements grouped together. Code blocks are distinct entities -- much like grouping bricks together forms a distinct structure. Blocks are the foundation behind if statements, loops, and functions, which you will meet later in this chapter.

Statements allow us to record simple truths about the world, and are the second building block in our journey to JavaScript competence. Before we continue, take note of the following syntax rule:

All JavaScript statements end in semicolons.

var jack = 60 // BAD
var jack = 60; // GOOD

Code blocks are contained in curly-braces.

{
    var x = 10;
    var y  = 3;
    
    x / y; // returns 3.33 
}

Variables

Do you remember solving for x in algebra class? As painful as that may have been, algebra introduced a powerful concept that we need to discuss -- the variable.

In JavaScript, variables act as placeholders in memory whose values can be changed on further notice. Consider: you know that your AdWords account will have a certain amount of spend tomorrow afternoon but you are unsure of how much. If we wanted to represent this in JavaScript, we'd declare a variable like this:

var spend; 

Notice that we did not assign a value to the variable, like we did in the earlier discussion. We could have, like so:

var spend = 0;

Pro Tip: We will use the special keyword var whenever we declare a variable for the first time.

Declaring a variable has a particular meaning, which is to say that we are telling JavaScript to make room in memory for an impending value. If we wanted to assign a value to our spend variable, we'd do it like so:

spend = 100; // units are in dollars

Pro Tip: After we declare a variable, we don't use var anymore.

We would refer to the variables up to this point as scalar in nature, which just means that our variables can only hold one value at a time. There are other types of variables at our disposal -- namely arrays and hashes -- which we will see later in this chapter.

Reserved Keywords

A quick word on a concept known as reserved keywords. There are certain words (aka keywords) that you cannot use as variable names -- these keywords already have a defined purpose within the language. Below is a list for your reference:

Reserved keywords: abstract, arguments, boolean break, byte, case, catch, char, class*, const, continue, debugger, default, delete, do, double, else, enum* , eval, export*, extends*, false, final, finally, float, for, function, goto, if, implements, import*, in, instanceof, int, interface, let, long, native, new, null, package, private, protected, public, return, short, static, super*, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, void, volatile, while, with, yield

Expressions & Operators

Let's spice up our discussion about statements. Previously, the statements that we used were very basic in that they only used the = sign (i.e. x = 30). In JS parlance, this is referred to as an assignment. We are allocating memory for an object of interest (a variable) and then stating, or assigning, a value to it. Assignment is the most elementary of what is known as expression.

Below is a formal definition of expression:

Pro Tip: An expression is a combination of one or more explicit values, constants, variables, operators, and functions that the programming language interprets (according to its particular rules of precedence and of association) and computes to produce ("to return", in a stateful environment) another value.

In order for JavaScript to understand our expressions, we use symbols that are known as operators. In the example above, the = sign acts an operator. Most operators are straight-forward and retain the same meaning that they have in traditional math classes.

Expressions are an essential part of writing JavaScript. In later chapters, we will need to perform tasks such as assigning bid adjustments based , comparing values, performing math (i.e. arithmetic), testing for truth, and checking text values. Expressions will allow us to accomplish these tasks. Here is a table that outlines the most important expressions using the variables declared below.

var x = 3;
var z = 9;
Operator Expression Type Expression Performed Example
= Assignment Giving a variable a value var x = 3; // returns undefined
= String Assignment Giving a variable a text value var name = 'Sarah'; // returns undefined but is 'Sarah'
== Comparison Equality test x == z; // evaluates to false
== String Comparison Equality test "John" == "John"; // evaluates to true
=== Comparison Strict Equality test x === z; // evaluates to false
!= Comparison Inequality test x != z; // evaluates to true
< Comparison Less than test x < z; // evaluates to true
<= Comparison Less than or equal to test z <= x; // evalutes to false
> Comparison Greater than test z > x; // evaluates to true
>= Comparison Greater than or equal to test x >= z; // evaluates to false
% Arithmetic Remainder x % z; // evaluates to 3
++ Arithmetic Increment (increase by 1) x++; // evaluates to 3, but x is now 4
-- Arithmetic Decrement (decrease by 1) x--; // evaluates to 4, but x is now 3
- Arithmetic Negation (multiply by -1) -z; // evaluates to -9
Math.pow Arithmetic Exponential Math.pow(z, 3); // evaluates to 729
&& Logical And (both expr. true) x < 4 && z > 1; // evaluates to true
|| Logical Or (One expr. true) x < 2 || z < 10 1; // evaluates to true
! Logical Not (Negates the expression) !x; // evaluates to false
test ? if true : if false Conditional Assigns value based on truth of first statement x == 3 ? 10 : 5; // evaluates to 10

Memorize this list as soon as you can. These operators will form the basis of all upcoming work that we'll do in the coming chapters. Note the following:

  • Order Of Operations (PEMDAS) - JavaScript respects the traditional PEMDAS (Please Excuse My Dumb Ass Students) operator hierarchy that most of us forgot about in algebra class. That, is PEMDAS or Parentheses, Exponentials, Multiplication, Division, Addition, and then Subtraction. Consider:

      var x = 8 + 4 * 3; // evaluates to 20 
    
      var y = 20 % 4 - 5; // evaluates to -5
      
      var z = (2 + 3) * 5; // evaluates to 25 
    
  • typeof. Use the typeof operator whenever you need to find out the type of data that a variable is.

      var x = 3;
    
      typeof(x); // 'number'
    
      var name = "John"; 
    
      typeof(name);  // 'string'
    

Data Types

The variables that we've seen thus far have only been integers; that is, whole numbers that are either positive, zero, or negative. Integers are very helpful for paid search metrics like impressions, clicks, and conversions (i.e. you can't have 0.3 conversion). Integers are discrete, meaning that they fall squarely on the number line.

But what if we want to store metrics like spend, click-through rate, or average CPC? Integers would fail us, since $2 is not the same as $2.50. I mention this to illustrate the need for different types of variables. Thankfully, JavaScript offers us a strong palette of data type options for us to work with.

Before diving in further, you should variable declaration is the same for all data types. We'll continue to use var to communicate to the JavaScript interpreter our desire for new variables.

Constants

Constants are values that never change -- they are considered immutable. In JavaScript, and in many other languages, constant variables are uppercase and usually declared at the beginning of a program.

var ROI_TARGET = 3; // a clients ROI goal 

var ERROR_CODE = 404; // HTTP response code considered to be an error 

var GOOGLE_SHEET = "https://docs.google.com/spreadsheets/example-sheet/edit";

Constant variables are known to be global in scope. This means that you can reference them anywhere in a script and JavaScript will know what you're talking about.

Constants are useful for noting truths and/or conditions that relate to your script. They can be any data type; whats key is that the value cannot change when your program is running.

Constants are also great for making your AdWords Scripts usable to the general public.

Pro Tip: Use constants for variables that could/should be changed by non-programmers, such as a Google Sheet URL or e-mail address.

Numbers

Number crunching, in one way or another, lies at the core of the online marketing experience. As mentioned, JavaScript provides both discrete numbers (i.e. clicks, impressions, and conversions), as well as continous or floating point numbers (i.e. spend, average CPC, CTR).

Integers (discrete numbers)

var clicks = 100; 
var impressions = 1000; 

Floating Point (Continuous numbers)

var ctr = clicks / impressions;  // returns 0.1
var spend = 505.13;
var cpc = spend / clicks; //  $5.0513

Pro Tip: If you need to convert from float to integer, use the parseInt() function . Likewise, if you need to convert from integer to float, use parseFloat() function. We'll discuss functions shortly but note the following examples.

parseInt(spend); // 505

parseFloat(impressions); // 1000

NaN And Infinity

JavaScript has two data types for expressing values that while, numeric, aren't actually number values -- NaN and Infinity. NaN stands for Not A Number. You'll encounter it in scenarios where the JS interpreter fails in a calculation. Similarly, Infinity represents a value that is greater than any other number. Don't worry too much about these data types. They're covered here simply so that you're aware of them.

Strings

Strings are what we commonly refer to as text. Think keywords, ad copy, sitelink text, etc.

var keyword = 'blue jeans';
var headline = "Official AdWords Scripts Cookbook";
var sitelink = "Save 20% When You Shop Now";

The astute reader will notice that I used single quotes for the first variable and double quotes for the remaining two. You can use whichever you're most comfortable with but I suggest sticking to double quotes whenever possible. Single quotes often have to be escaped, while double quote strings rarely do. Consider:

var name = 'Martin O'Malley'; // Fails 

var name = 'Martin O\'Malley'; // OK

var name = "Martin O'Malley"; // better

If numeric variables are yin then string variables are yang. Manipulating text efficiently lies at the heart of many scripting tasks. Automating keyword match type variations, generating countdown ad copy, and generating ad group names are just three tasks off the top of my head that require manipulating text.

There's even an entire field of study devoted to manipulating text -- regular expressions, which we will use in later chapters.

Boolean

There are times when you want to store truth rather than a number value. For example, consider the following example:

var maxCpc = 1.0; // current max CPC is $1.0;
var firstPageCpc = 2.0; // current first page CPC is $2.0

var isBelowFirstPageBid = maxCpc < firstPageCpc; // evaluates to true 

In the example above, the isBelowFirstPageBid variable is boolean; it can be either true or false. Boolean variables allow us to ask 'yes or no', 'hot or cold', 'in or out' types of questions -- often referred to as 'bimodal' categories.

Common Scenarios Involving Boolean variables:

  • Determining whether there are still keywords to be reviewed
  • Deciding if an adgroup has the sufficient number of ads
  • Determining if a max CPC bid is beyond a certain threshold

Time

- Representing time 
- Time arithmetic

Undefined and Null

Before we dive into undefined and null values, I want you to think about the concept of zero. Its neither positive nor negative. Its nothingness. Everyone knows what it means to have zero dollars. We also know what it means to make room for an upcoming event even though we don't have specific information about it. It'd be nice to have a way to express this concept in JavaScript. That's where undefined and null come into play.

Undefined variables are effectively placeholders in that they have been declared but have not been assigned a value. If you declare a variable but don't assign it a value, it will be undefined. link.

var spend; // undefined 

Pro Tip: Don't assign undefined to a variable. That's what null is for.

var clicks = undefined; // WRONG

Null is the equivalent of zero in JavaScript. It's a placeholder that we can assign whenever we want to keep a variable around but don't want to give it a value.

var impressions  = 0;

impressions == null; // false since impressions has a value

impressions = null; // now null
 
 impressions == null; // true 

Again, we will rarely assign null to variables in upcoming scripts but its important to be aware of undefined and *null.

Data Structures

Scalars

At this point, we've progressed from variables that were strictly whole numbers to variables that can deal with decimals, text, truth, and nothingness -- quite the journey!

Each of these data types have a common characteristic: they are scalar values.

Reminder: scalar variables are those that only hold one value at a time.

Scalar values are what most people think of if variables are the hot topic of discussion. Its not wrong to think of scalar values as one-dimensional.

The problem is that many of the ideas that we encounter in paid search are not scalar in nature. For example, think about an AdWords campaign. It holds many ad groups. How do we account for this/

// campaign X has 3 ad groups: A, B, C
var campaign = ???; // how do we show the ad groups? 

Arrays

Not all values are scalar. For example, if you were to go grocery shopping after work, you'd probably employ a grocery list. Each item on the list is distinct from the others.

// Grocery List: 'Eggs', 'milk', 'bread', 'butter'

List (n) - a number of connected items or names written or printed consecutively, typically one below the other.

In JavaScript, lists are called arrays. Formally, arrays are data structures that contain elements, which are indexed by their place in the array. Declaring an array looks like this:

var groceryList = []; // the brackets tell JavaScript that we want an empty array. 

groceryList =  ['butter', 'bread', 'wine', 'cheese']; // assigning elements to an array

Our grocery list has four items or elements, which in this case are strings or text variables. JavaScript arrays are zero-based, which is counter intuitive if you've never seen this convention before. In English, if we wanted to refer to the 'butter' item of the grocery list above, we'd say that it is the first item on the list. In JavaScript, 'butter' is actually element zero of the list. The first element would actually be 'bread'.

groceryList[1]; // 'bread'  -- not what we want!

groceryList[0]; // 'butter' -- correct!

All arrays have attributes -- or values -- that describe their current disposition, or state. These attributes are called properties. The length property is a key property that you should remember. An array's length property shows how many items the array currently holds.

groceryList.length; // evaluates to 4 

Pro Tip: You don't set properties. JavaScript handles this for you.

In addition to properties, all arrays have some built in functionality -- known as methods -- that are worth noting here.

Pro Tip: Arrays are also known as stacks, like a stack of dishes.

The act of adding an item, or element, to the bottom of an array is called pushing that element onto the stack.

groceryList.push('cereal'); // returns 5, the new array length
groceryList[4]; //  returns 'cereal'

Adding an item to the beginning of an array is known as unshifting that element onto the stack.

groceryList.unshift('trail mix'); // returns 6, the new array length
groceryList[0]; // returns 'trail mix', the new first item in the array

Removing the last item from an array is known as popping that element from the stack.

groceryList.pop(); // returns 'cereal', the last item in the array 
groceryList.length; // return 4, the new count of array items  

If you wanted to remove the first item from the stack, that would be called shifting an element off the stack.

groceryList.shift();  // returns 'butter', the first item in the array
groceryList[0]; // returns 'bread', the new first item in the array
groceryList.length; // returns 3	

Arrays are one of the bread-and-butter data structures that we use when writing AdWords Scripts. Don't fret if any of what we just covered seems fuzzy -- there will be countless opportunities to ingrain array handling in subsequent chapters.

Recap: Arrays are the equivalent of 'lists' in JavaScript. They let us store scalar elements (i.e. numbers, strings, booleans, etc) in a way that will allow us to access the data later.

Objects

Before moving with our data structure discussion, lets revisit the issue of how to present a AdWords campaign in JavaScript.

At the time, scalar variables were our only means of expressing ourselves in JS. It was noted that a campaign had one or more adgroups; this was an issue since there was no way of keeping a list in a world that only has single values. Arrays solved that problem for us.

var brandCampaign = ['adgroup1',  'adgroup2', 'adgroup3', 'adgroup4'];

Something still feels off. The notion of a campaign implies more than just what adgroups that contains. Campaigns also have attributes that, without them, nullifies the idea of a campaign. For example, all campaigns have names and daily budgets. Campaigns also have various settings, like ad rotation preference and languge.

There needs to be a data structure that lets us keep one or more pieces of information about an object in JavaScript. This would allow us to store all of the unique aspects about a campaign in one place and subsequently allow us to retrieve these values later on.

In JavaScript, we call this idea an Object. Objects look like this:

var campaign =  {};
campaign.language = 'English';
campaign.budget = 100;
campaign.adgroups = [];
campaign.name = 'BRAND_CAMPAIGN';

campaign.name; // 'BRAND CAMPAIGN'

Alternatively, we could have created our campaign object like this:

var campaign = {
	name: 'BRAND',
	language: 'English',
	budget: 100,
	adgroups: [],		
};	

campaign.name; // 'BRAND_CAMPAIGN'

campaign.budget = 500; // increase budget from $100/day to $500/day

campaign.adgroups.push('EXACT_MATCH'); // Add Exact match adgroup 

campaign.adgroups; // [ 'EXACT_MATCH' ]

Our JavaScript campaign now aligns closely with how we'd describe it in real life. Note that we can combine scalars and arrays to compose an object that resembles real life.

Believe it or not, we have enough tools in our toolkit to model real-life entities in JavaScript.

Check Your Understanding: Model an AdGroup using objects.

Pro Tip: Objects allow us to model and manipulate AdWords entities that we would normally have to work with in the UI.

Functions

Thus far, we can express ourselves in JavaScript with statements and data structures (i.e. scalars, arrays, and objects).

Reminder: Statements let us to do tasks like assigning values, compare values, test truth via Boolean values, and do math.

Data structures let us describe real-world values, lists, and entities programmatically.

Until now, our expressions and data structures have been created in a vacuum. I've simply shown you how to create expressions and three different ways to describe your data. Unfortunately, statements and data structures by themselves don't amount to what most would consider to be an program or AdWords Script.

But what exactly is an AdWords Script?

An AdWords Script is a set of instructions, also known as an algorithm for completing a specified task. You can think of an algorithm as a recipe.

Imagine that you need to explain to a new employee how to calculate keyword bids based on ROI. You might explain the process like so:

"To calculate the new bid, first you need to find out both the average order value and keyword conversion rate. Then, you multiply the average order value by the keyword's conversion rate to get to the new bid amount."

These instructions above are both specific and formulaic in nature. It doesn't matter who actually performs the steps outlined above; it just matters that the work gets done. This employ would need to have A & B before doing C.

In JavaScript, this idea is called a function. A function is one or more statements grouped together to perform a task. Here's our bid calculation function:

function calculateBid(averageOrderValue, conversionRate) {
	return averageOrderValue * conversionRate;
}

Here's a couple things to note about functions: * Functions can be called. This just means that we can tell JavaScript to run them whenever we need a task performed.

	calculateBid(averageOrderValue, conversionRate); // example of calling a function
  • Functions accept arguments, also known as paramaters, which are inputs that we supply. We saw this with our bid calculating function -- we gave it inputs and expected it to give back an updated bid. Arguments are optional.

Pro Tip: Planning out what inputs your functions will need is an integral aspect to writing scripts.

  • Functions return a value using the return keyword.

      function doSomething() {
      	return 1 + 1; // 2 
      } 
      
      var x = doSomething(); 
      x; // 2 
    
  • Functions are considered first class citizens, meaning that they are considered on par with other variable types (i.e. numbers, strings, arrays, etc). This distinction will have far-ranging implications later in the book.

      var cpcBid = function(averageOrderValue, conversionRate) {
      	return averageOrderValue * conversionRate; 
      };
    
      cpcBid(39.99, 0.05); // returns 1.995...
    
  • Functions don't always have to return a value. In fact, one situation where this applies is the act of running an AdWords Script at all.

Pro Tip: All AdWords Scripts live inside a function called main().

function main() {
	var averageOrderValue = 29.99;
	var conversionRate = 0.02;
	
	calculateBid(averageOrderValue, conversionRate); // returns $0.5998
}

Code Blocks revisited

In the last section, we saw that statements and data structures alone don't amount to AdWords Scripts. We needed to group these statements and data structures into code blocks, which then transform them into distinct entities. Functions are one way of creating code blocks but there are other types of code blocks to use.

Decision Making In JavaScript

Like most programming languages, JavaScript allows us to employ conditional logic, colloquially known as if/else statements. There will be many scenarios where will want to test truth in some way before acting -- which is exactly what we do when performing AdWords management tasks manually.

Here are a couple examples of a vanilla if statement.

  • "If the maxCPC is above $3 then X."

      if (maxCpc > 3) {
      	// do something
      } 
    
  • "If MTD spend is over $50,000 then Y"

      if (mtdSpend > 50000) {
      	// do something 
      }
    

In the examples above, if maxCpc is less than $3 or MTD spend is less than $50K, nothing occurs. A single test can be useful but sometimes you will want something to happen if the test statements are not true. Else statements accomplish this for us.

  • "If a keyword has spent more than $100 and has 0 conversions then Z"

      if ((keywordSpend > 100) && (keywordConversions == 0)) {
      	// do something 
      }  else {
      	// do something else 
      }
    
  • "If keyword match type is broad or keyword has a CTR less than 5%"

      if ((matchType == 'BROAD') || (ctr < 0.05) {
      	// do something 
      }  else {
      	// do something else 
      }
    

Pro Tip: When testing equality, use == or ===, never =, which is only for assignment.

var x = 10;

if (x = 3) { // always will be true b/c you're telling  JS that x is equal to 3
	// do something
}

if (x == 3) { // compare if x is equal to 3 
	// do something
}

Sometimes there will be scenarios where you'll want to test another truth when the first statement is false. Use If/else statements in these scenarios.

if (matchType == 'BROAD') {
	// do something
} else if (matchType == 'PHRASE') { // match type isn't broad but is it phrase?
	// do something
		
} else { // match type must be Exact
	// do something	
}

Even though we will use if statements frequently in later chapters, do know that its possible to accomplish decision logic without them. I'll show you how to accomplish this in chapter 5, where we discuss the concepts of selectors and iterators.

ProTip: Only selecting items to act on based on criteria is an alternative approach to using if/statements.

switch statements

In the last example, did you notice that there were three specific outcomes that we tested for (i.e. the keyword match types)? Even though this approach works, it feels cumbersome to need to write an if/else for each possibility -- especially if there were a lot of possibilities to consider.

Switch statements let us run code blocks based one or more defined scenarios. For example, lets suppose that we only want to act on broad-match keywords.

switch(matchType) {
	case 'BROAD':
		// pause keyword 
		// create broad-modified-match version 
		break;

	case 'EXACT':
		// don't do anything 
		break;

	case 'PHRASE': 
		// don't do anything
		break;
}	

Pro Tip: break tells JS to stop the current code block, without it the different scenarios would run into each other.

We could rewrite this code, known as refactoring like below to make it more efficient.

switch (matchType) {
	case 'BROAD':
		// pause keyword 
		// create broad-modified-match version 
		break;
	default: // anything not broad
		break;
}

Pro Tip: default is the catch-all case scenario.

Block Type | Definition| --------------|--------------|------------ Code block | One or more JavaScript statements |
Function | A code block that runs when called and can return a value If/else statement | Tests truth and runs a code block based on result Switch statement | Tests truth and runs code block if there a case; runs default otherwise

Iteration

To recap, we saw that code blocks are one or more JavaScript statements and/or data structures grouped together.

Functions are code blocks that can be run when they are called -- effectively making them mini-programs.

If/else and switch statements are code blocks that run based on truth.

Pro Tip: The JavaScript interpreter will move on as soon as the code block (or lack thereof) of the decision logic completes.

Loops are the next logical step in our discussion of code blocks. Loops give us the power concept of iteration. Iteration is the idea that a code block will be repeated until it no longer makes sense to do so.

Loops are the reason why you'll be going home early and your coworkers will be staying late. Why?

Consider a situation where you need to review 5,000 keyword bids for an account based on ROI. All bids need to be updated in the UI. You despair because even though it only takes 15 seconds to complete the task, you'll need roughly 21 hours to finish!

(15 sec * 5,000 keywords) = (75,000 seconds / 60 seconds per min) = 1,250 minutes / 60 = 21 hours!

Fortunately, you now have the tools needed to automate this process and sketch out an algorithm.

// create a function to calculate a keyword bid based on ROI 

function calculateBid(averageOrderValue, conversionRate) {
	return averageOrderValue * conversionRate;
}

// create a function that updates the keyword's max CPC
function updateKeywordCpc(cpc, keyword) {
	keyword.cpc = cpc;
	return keyword;
}

// create a main function to run program 

function main() {
 	// store the list of keywords to update in an array 
 	var keywords = getKeywords(); // assume this exists and gives all keywords
 	
 	// use a loop to test if there are remaining keywords in the array  
 	
 	while (keywords.length > 0) {
 		var keyword = keywords.shift(); // remove the first item from the array 
 		var newBid = calculateBid(keyword.averageOrderValue, keyword.conversionRate);
 		
   	 	// calculate max CPC and update the keyword  if the bid is greater than $0.05
   	 	// leave the keyword bid alone if the test fails
 		if (newBid > 0.05) {
	 		updateKeywordCpc(newBid	, keyword)
 		} 		 		
 	}
 	// stop script when there are no more keywords  
}

Voila! What would have taken 21 hours will now be completed significantly faster. Computers are fantastic for unflinchingly repeating tasks; loops allow you to tap into that power.

Notice that the loop above allowed you to apply the same code logic to each keyword individually; very similar to how an assembly line works.

Loops come in several flavors, namely while loops and for statements. Here's how we could have expressed the code above using for-loops.

for (var x = 0; x < keywords.length; x++) {
	var keyword = keywords[x]; // get the x-th keyword from our list
 	// ..
}

Pro Tip: Loops combine decision-logic with the idea of recurrence. Recurrence means that a script will keep running a code block until there is a reason to stop doing so.

Summary

If you made it this far, you have all the tools necessary to write Google AdWords Scripts! Congratulations! Don't worry if some of the concepts above are still fuzzy -- what is important is that you're aware of them.

In the next chapter, you will use the concepts from this chapter and write your first AdWords Script!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment