Google Ads Scripts 101Chapter three

JavaScript Basics

This intro to JavaScript is for anyone learning JavaScript for any purpose. Although part of a series for Paid Search practitioners, this chapter covers only universally-applicable JavaScript code and concepts. After the first paragraph, this chapter is not specific to Paid Search in any way.

AdWords Scripts are simply JavaScript, imbued with some Google AdWords concepts and libraries.  As Google states, an “entry-level familiarity with JavaScript is needed” to get started, so here is a crash course. If you’re familiar with JavaScript, you can jump ahead to the advanced AdWords Script chapter.

Note: This is a practical introductory guide to JavaScript. Many concepts are simplified, sometimes at the expense of thoroughness and preciseness. If JavaScript was our universe, this guide glosses over the gory quantum details, giving only the simpler laws and abstractions that govern the day-to-day for most mortals.

JavaScript is most well-known as part of the triumvirate of technologies upon which web content is built.  Content is structured using HTML, styled using CSS, and JavaScript … well, does everything else.  The internet would be a far plainer place without JavaScript.  This “client-side JavaScript” lives on webpages and runs right in your browser, but JavaScript can also run on servers to conduct back-end tasks.  AdWords Scripts are an example of the latter.

To be able to understand and edit AdWords scripts, you’ll need to understand its syntax. Syntax is the set of the vocabulary and grammar rules for the language.

Java and JavaScript are commonly confused, but they are completely different languages.

Let get started by introducing the basic syntax elements of JavaScript.



A comment is a section of a script that will be ignored when the script is run.

Comments are primarily used to provide documentation and explanations of what a particular piece of code does in plain English.  Scripts often begin with a comment section, which gives general information about the entire script, such as an overview of what it does, the author, and sometimes URLs for more detailed documentation.

There are line comments, which start with // and continue until the end of the line.

// This is a line comment.

There are also block comments, which start with /* and end with */ and can span multiple lines.

Comments can used to temporarily disable a piece of code, which can be helpful for testing. For example, you can comment out lines of code one by one, each time re-running the script, to hone in on is throwing things off.


Structure & Punctuation

A statement is an instruction.  Just like an instruction in a human language, a JavaScript statement can be as simple as one word, or consist of multiple phrases (called expressions).  But unlike a person, if you instruct using perfect spelling and grammar, a computer will always do precisely as it’s instructed.

Scripts are made up of many statements, which are executed from top to bottom, left to right.

Each statement should end with a semicolon.  Semicolons indicate that the statement is complete, and should execute before proceeding to the next statement.

Whitespace (basically, spaces and line breaks) can impact functionality in many computer languages—but not in JavaScript.  In JavaScript, whitespace is used only for readability and has no functional impact.  One effect of this is that a single statement can span multiple lines.

This is a statement:

sentences = text.split( '. ' );

This code will do the exact same thing …

sentences=text.split('. ');

…and so will this:

'. '
Convention: Breaking up long statements into multiple lines is common practice, because it is easier to read (and prevents you from having to scroll horizontally as when reading scripts).

Pro Tip: There is one case where whitespace is actually functional: newlines can be used in place of semicolons to separate statements.  But this can cause issues in fringe cases, so as a general rule semicolons should always be used.


Intro to Functions

A function is a reusable piece of code, like a sub-script within the script.

Scripts are frequently organized into functions for a number of reasons:

  • Simplification of the main script code.  All the detailed code is abstracted into a descriptive function name, making the main script shorter and easier to read and follow.
  • If the same algorithm, calculation or process is used multiple times in a script, using a function minimizes the need for duplicate code.
  • It makes it easier to reuse bits of useful across multiple scripts.

Functions break up the top-to-bottom execution order of a script, because function code is run exactly where it is written.  Say you’re reading an article, and the writer begins the article with a glossary of jargon. You skim the glossary, not for comprehension, just to make yourself aware of the jargon you can expect to see.  Every time you encounter jargon, you jump back to the glossary to read the definition before continuing the sentence. The jargon would be function names, and the way you’re reading represents the nonlinear order of how scripts run.

First, you’ll see the function definition, which indicates the name of the function and its code:

function makeItRain(){
    // Code to make it rain goes here.

But that code is not executed until the function is called.  Functions are called using the function name, followed by a set of parentheses:


A function can be called repeatedly—and every time it’s called, the function code re-runs.

There are a variety of built-in functions available.  If you a function is called but you see no function definition, then it is a built-in function.  These work exactly the same way as custom functions.

You’ll learn more about functions later in the guide, but for now just understand that a function is a set of code that can be called from anywhere in the script.

// Assign code to the function name: 'makeItRain'.
function makeItRain(){
    // Code to make it rain goes here.

// Make it rain once ...

// ... twice ...

// ... three times!

Get it? Just to make sure, here is one more example:

// This function "returns" the result of
//  adding the numbers two and three.
function addTwoAndThree() {
  return 2 + 3;

// Wherever this function is called, it will
//  be replaced with the returned value.
addTwoAndThree();     // 5
1 + addTwoAndThree(); // 6



A value is a piece of data.

A value written directly into a script is said to be literal.

// a literal number three

A literal value is only available to the code once, exactly where it is literally written. In order to be accessed repeatedly (and possibly manipulated), a value must be assigned to a variable.



A variable is a named reference to a value.

A variable is created with the keyword var, and can be assigned a value using the equals sign.

// Create variable 'age'.
var age;
// Assign 'age' a value of three.
age = 3;

This can be combined into a single line:

var age = 3;

An existing variable can be re-assigned, which changes its value from that point forward. Oftentimes variables are assigned new values multiple times.

var age = 1;
// Variable 'age' equals one.

age = 2;
// Now variable 'age' equals two.

age = 3;
// Now variable 'age' equals three.

After it is created, a variable can be referenced using the variable name.

var age = 3;
var yrsOld = age;
// Now both 'age' and 'yrsOld' equal 3.
Convention: As seen in the example code above, both the variable value and type can be changed.  But in practice, it’s best for each variable to have the same value type throughout the entire script, to keep the logic easy to follow.


Variable Names

A variable’s name is how it is referenced throughout the script, used as a placeholder for the variable’s value.

How a variable is named has no functional effect on the script.  Names are chosen solely for readability, and should reflect the variable’s semantic purpose in the script.  Ambiguous names (like those used in many of the code snippets in this guide) should never be used in actual scripts.  One exception is that single-letter names are often given to variables that are simple counters.

Variable names can contain letters (case-sensitive), underscores, and dollar signs.  They can also contain numbers, but not as the first character.

Convention: Always start your variable names with a lowercase letter.  This convention will help avoid conflicts with most built-in variables, which generally start with uppercase letters.

Capitalize the first letter of each subsequent word in your variable name in a convention known as “lowerCamelCase” or “camelBackCase”. This keeps your variables readable without restricting you to single-word variable names.

There are some words that should never be used as a variable name, because they have special meaning in JavaScript.  You’ll learn about a few of these in this guide.

  • null
  • true
  • false
  • undefined
  • NaN
  • Infinity
  • eval
  • arguments
  • var
  • break
  • case
  • catch
  • continue
  • debugger
  • default
  • delete
  • do
  • else
  • finally
  • for
  • function
  • if
  • in
  • instanceof
  • new
  • return
  • switch
  • this
  • throw
  • try
  • typeof
  • void
  • while
  • with
  • class
  • const
  • enum
  • export
  • extends
  • import
  • super
  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield


Built-In Variables

JavaScript has a few built-in variables that are always available.  You’ll learn about some of them in the next section, but know that these exist, and scripts should not use any of these names for custom variables:

  • Math
  • JSON
  • Function
  • Object
  • Array
  • Boolean
  • Date
  • String
  • Number
  • Error
  • EvalError
  • InternalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError
  • RegExp
  • Promise
  • Set
  • Map
  • WeakSet
  • WeakMap



You remember functions, right? Let’s go over it again, this time building on your understanding of values and variables, and dig into what makes functions so useful beyond just being reusable.

A function is effectively a variable. Function names follow the same rules as variable names. But instead of a value, it has a set of code.  And instead of being referenced, it is called (which is just like referencing a variable, except with parentheses after the name).

Just as a reference to a variable is replaced with the variable’s value, a function call is replaced with the function’s returned value.  In the function code, a value is returned with the keyword return:

function whoAmI(){
    return "I don't know.";
whoAmI(); // "I don't know."

If a function doesn’t return anything it’s said to “return undefined.” (You’ll learn more about “undefined” in the following section.)

Functions can have input variables, which are defined as parameters in the function definition, whose values can be passed as arguments in the function call:

function theFunc( param1, param2 ){
    // Function code goes here,
    // which has access to the 
    // values of arg1 and arg2 
    // through the variable names 
    // param1 and param2.
theFunc( arg1, arg2 );

Think of arguments as function “inputs”, which influence the function “output” (the return value).

function whoAmI( name ){
    return "I'm " + name + "!";
whoAmI( "Jax" ); // "I'm Jax!"

Functions also have access to variables that were created outside of the function.

var myName = "I don't know";
function myNameIs( name ){
    myName = name;
function whoAmI(){
    return "I'm " + myName + "!";
whoAmI(); // "I'm I don't know!"
myNameIs( "Jax" );
whoAmI(); // "I'm Jax!"
Although functions can access variables that were created outside the function, it’s generally best to avoid it. Keep functions self-contained by having them accept all neccessary values as parameters. This will make your code cleaner, easier to read, and easier to troubleshoot.


Global Functions

JavaScript has a set of built-in functions.  These are called global functions because they are available anywhere in any script.  Here are a few:

  • parseInt()
  • parseFloat()
  • isFinite()
  • isNaN()
  • decodeURI()
  • encodeURI()
  • decodeURIComponent()
  • encodeURIComponent()



There are also a variety of built-in functions that can only be called through variables, called methods.  A method is a function that is owned by and specific to a variable, and can only be accessed through that variables.  A method can be called by following the variable reference with a period, then the method like any other function call:

var name = "JAX";
name.toLowerCase(); // "jax"

Which methods are available on a particular variable is determined by the variable’s value type.  You’ll learn about various value types and their most useful methods in the next section.



There are other global functions made available as methods of built-in global variables called libraries.  Here are libraries you may encounter and example methods:

  • JSON (Reference)
    • JSON.parse()
    • JSON.stringify()
  • Math (Reference)
    • Math.round()
    • Math.sqrt()
There is no need to try to memorize any of the built-in functions/methods.  Documentation on each’s purpose, parameters, returned values, usage examples, and more are always a few keystrokes away in a wealth of online resources (see the Resources section).  Simply do a web search for “javascript” and function/method name.



The type of a value indicates how its data is structured and how it can be manipulated.

There are five basic types:

  1. Boolean
  2. Number
  3. String
  4. Regex
  5. Date

And two complex types, which can contain multiple values:

  1. Array
  2. Object

Pro Tip: There’s actually one more type: function.  (When I said that “a function is effectively a variable”, it wasn’t just a metaphor.) The function definition is the value, and function literals not assigned a function/variable name are called anonymous functions. Learn More.

There are also two special “blank” values, which don’t fall under any of the types above: null and undefined. Variables have a default value of undefined until they are assigned a value, and null is a generic blank value which can be used to explicitly indicate a variable intentionally has no value.  Example:

var name; // undefined
// 'name' is blank by default.
name = null;
// Now 'name' is explicitly blank.

null and undefined are the only values with no methods.

Each type has its own methods and own value literal syntax, so let’s take a look at each type:

Let’s review the five basic types of values.



There are two boolean values: true and false.

var jaxIsYoung = true;
var jaxIsOld   = false;



Number literals can be written as integers, decimals, or in exponential form.

var age     = 3;
var pi      = 3.14159;
var leagues = 2e4; // 20,000



A string is text, consisting of zero or more characters.  String literals are written by surrounding the text with either single or double quotes.

var name     = 'Jax';
var greeting = "Hi, I'm Jax!";
When your string includes a single quote, you’ll need to use double-quotes to surround your string, or escape the single quote by preceding it with a backslash.  Vice-versa for a string containing a double-quote.

Here are some useful string methods.

trim() strips leading and trailing whitespace.

greeting = "   hi   ";
greeting.trim(); // "hi"

toLowerCase() and toUpperCase() convert all characters to a single case.

greeting = "Hello!";
greeting.toLowerCase(); // "hello!"
greeting.toUpperCase(); // "HELLO!"

indexOf() searches for specific text within the string (passed as an argument) and returns the numerical position of the matched text (first character considered the zeroth position), or -1 if the text is not present.

greeting = 'hi Philadelphia!';
greeting.indexOf('hi'); // 0
greeting = 'hey Philadelphia!';
greeting.indexOf('hi'); // 5
greeting = 'hey San Diego!';
greeting.indexOf('hi'); // -1

Note that none of these methods actually modify the variable’s value, but simply return the modified value.

greeting = "Hi";
greeting.toLowerCase(); // "HI"
// The above line returned "HI", but
//   the variable was not assigned
//   the returned value, so:
//   greeting = "Hi" (unchanged)
greeting = greeting.toUpperCase();
// This time we assigned the
//   returned value to the variable:
//   greeting = "HI"

You can find a reference of all string methods on MDN.

Strings also have a length property, which is not a function but just a number indicating number of characters in the string.

name = 'Jackson';
// name.length = 7
name = 'Jax';
// name.length = 3
name = '';
// name.length = 0



A regex, or regular expression, is a special query pattern used for searching and matching strings. You may already be familiar with regex because it can be used in many platforms and applications.  If you are not familiar with regex, check out this quick-start guide.

In JavaScript, a regex literal is written by enclosing the regex expression with forward-slashes.

// Regex to match start of a URL.
var matchUrl = /^https?:/;

If a forward-slash is part of the regex expression, it needs to be escaped by preceding it with a backslash.

// Regex to match start of a URL.
matchUrl = /^https?:\/\//;

Regex flags can be added after the rightmost slash.

// Now regex is case-insensitive
// since we added the 'i' flag.
matchUrl = /^https?:\/\//i;

The same regex can also be created this way:

myRegex = new RegExp( '^https?://', 'i' );

This is useful for when the regex expression is not predetermined.

In JavaScript, regex can be used to:

Determine if a string matches a pattern:

/^http:/.test(""); // true
/^http:/.test("not a url"); // false

Extract pattern matches from a string (learn about the return value here):

var m = /(.*)=(.)/g.exec("2+2=4");
// m = ["2+2=4", "2+2", "4"]



A date is a timestamp, specific to the millisecond.

A date can be created by setting values for year, month, day, hour, minutes, seconds, and milliseconds.

var birthday = new Date( 2013, 4, 4, 4, 3, 1 );
// May 4, 2013 @ 4:03:01

But only year and month are required; the date need only be set to the specificity needed by the script.

var birthday = new Date( 2013, 4, 4 );
// May 4, 2013

Note that January is zero, and December is eleven.  If you passed twelve as the month value, it would map to January of the following year.

var xmas = new Date( 2016, 12, 25 );
// Jan 25, 2017 <- whoops, not xmas!
Dates can also be created using a single string that specifies the date, instead of multiple number values. But if the string is not formatted correctly, the date may have an unexpected value.  See examples for acceptable formats here.

If a date is created without setting any values, it will default to the current date/time (as set by the computer on which the script is running).

var now = new Date();

This allows us determine how far in the future or past a second date is, which can be very useful.

var now = new Date();
var xmas = new Date( 2016, 11, 25 );
var millisecondsAway = xmas - now;
var daysAway = 
  millisecondsAway / 1000 / 60 / 60 / 24
JavaScript dates are timezone aware. This is important to keep that in mind when dealing with date values from multiple sources.



An array is an ordered collection of values.

nicknames = [ 'Jax', 'Jah', 'Jay' ];

An array’s values are mapped, or indexed, by integers.  Indexing is done automatically, starting at zero, incrementing for each item.  So the first value is at index 0, the second at index 1, and so on.

Each item in an array can be accessed by placing the index within square brackets after the variable reference.

nicknames[0]; // 'Jax'
nicknames[1]; // 'Jah'
nicknames[2]; // 'Jay'
Starting at zero instead of one may seem strange to you, but it is very common in the world of computer science.  Don’t worry; you’ll get used to it pretty quickly!

Because they are indexed numerically, arrays have an intrinsic order.  So, arrays are well-suited to represent an ordered dataset where order matters (such as a queue or an alphabetical list).

Arrays can contain any number of values—even zero.

nicknames = []; // empty array
// No nicknames! Just call me 'Jackson'.

To add an item onto the end of an existing array, use the push method:

nicknames = [];
// Okay, you can call me 'Jax'.
nicknames.push( 'Jax' );
// nicknames = [ 'Jax' ];

To remove the last item in an array (and return it), use the pop method:

// nicknames = [ 'Jax' ];
nicknames.push( 'Jackie' );
// nicknames = [ 'Jax', 'Jackie' ]
// I will not answer to 'Jackie'!
nicknames.pop(); // 'Jackie'
// nicknames = [ 'Jax' ]

You can find a reference of all array methods on MDN.

Similar to strings, arrays have a length property, which is not a method, but a special property that always indicates the number of items in the array:

nicknames = [ 'Jax' ];
// nicknames.length = 1;
nicknames.push( 'Jah' );
// nicknames.length = 2;

This is how you operate on all items of an array (this contains operators and a loop which is covered in following sections):

// nicknames = [ 'Jax', 'Jah' ]
var i, nickname;
for( i=0; i < nicknames.length; i++ ){
 nickname = nicknames[i];
 say( 'Some call me '+nickname+'.' );
// Some call me Jax.
// Some call me Jah.

Values in an array can be of any type—even other arrays.  An array within an array is known as a two-dimensional array.  If a row in a spreadsheet was an array, the entire sheet would be a 2-D array.

var table = [
 [ 'A1', 'B1' ],
 [ 'A2', 'B2' ],
 [ 'A3', 'B3' ],
myArray[0];    // [ 'A1', 'B1' ]
myArray[0][0]; // 'A1'
myArray[2][1]; // 'B3'
myArray[2][2]; // undefined



An object is an unordered collection of key/value pairs.

var kid = {
  'age'       : 3,
  'name'      : 'Jackson',
  'nicknames' : [ 'Jax', 'Jah' ]

Remember that white space just used to format code.  This code creates the same exact object:

var kid = {'age':3,'name':'Jackson'};

An object’s values are mapped by strings called keys.  When a value is added to an object, it is added using a particular string, and then that string can be used to request that particular value from the object. That string is the value’s key.  If a coatcheck were an object, the coats would be values, and the numbers the attendant uses to keep track of coats would be keys.

Items in an object can be accessed with the same bracket-syntax used for an array:

kid['age'];  // 3
kid['name']; // 'Jackson'

Items in an object can also be accessed can also be accessed using dot notation:

kid.age;  // 3; // 'Jackson'

Either syntax can also be used to add a new key:

kid.nicknames = [ 'Jax', 'Jah' ];

Or to change the value of an existing

kid.nicknames = [ 'Jax', 'Jah' ];

This is how you operate on all keys or values of an object (this contains operators and a loop which is covered in following sections):

// kid = {'age':3,'name':'Jackson'}
var key, value;
for( key in obj ){
 value = kid[key];
 // Code to deal with a
 //   key/value pair goes here.
 say( 'My' + key + ' is ' + val );

// My age is 3.
// My name is Jackson.

Like an array, an object can contain any number of values, and those values be of any type, including other arrays and objects.

var kids = {
    'firstborn' : {
        'name' : 'Jackson',
        'age'  : 3
    'middleChild' : {
        'name' : 'Jazmine',
        'age'  : -0.65
    'theBaby' : {
        'name' : 'Isaiah',
        'age'  : undefined
kids.firstborn.age; // 3;  // 'Isaiah'

Objects are useful for representing a singular item or concept (e.g. a product, with name, sku, and price attributes), or storing a collection that has a specific unique id system (e.g. a set of product objects, mapped by their skus).

Pro Tip: Any given dataset can be represented by either an array or an object. But, usually one is better suited than the other, based on the structure of the dataset.  For instance, the previous example would be better represented as an array of objects:

var kids = [
        'name' : 'Jackson',
        'age'  : 3
        'name' : 'Jazmine',
        'age'  : -0.65
        'name' : 'Isaiah',
        'age'  : undefined



There are a number of operators in JavaScript, many of which reflect how they would be written in a mathematical expression.  However many can be used for types other than numbers.


Mathematical Operators

+ add
- subtract
* multiply
/ divide

As you may have guessed, these are used with numerical values.

To use exponents/roots, do not use a caret (^)!  The caret is an advanced operator that does something totally different (so using it will allow your script to run, but return incorrect values—an error which can be hard to catch).  Instead use the built-in function: Math.pow(base,exponent).

Expressions with multiple mathematical operators will be evaluated according to the standard mathematical order of operations. In case you don’t remember PEMDAS, here’s a refresher:  Expressions within parentheses are evaluated first, then exponents, then multiplication/division, then addition/subtraction; other than that expressions are evaluated left-to-right.

If using multiple operators in a single expression, it’s wise to break the expression down into pieces using parentheses.  Even if a complex expression is evaluated correctly according to order of operations, using parentheses can improve readability, making it easier to read and understand the expression.  (Double up on readability by using parentheses AND explaining a complex expression using a comment!)

Pro Tip: There is a special division operator called “modulo”: %.  It is like division, but instead of returning the exact division result it does integer division and returns the remainder. It is useful for determining whether a number is a factor of another number.


Concatenation Operators

The plus sign doubles as a concatenation operator for strings:

+ concatenate two strings
+= append to a string variable


name = "Jax";
greeting = "Hi!"
greeting += " I'm " + name + ".";
// greeting = "Hi! I'm Jax."

If the concatenation operator is used between a string and another type, the non-string value will be coerced into a string. Example:

age = 3;
greeting += " I'm " + age + " years old.";
// greeting = "Hi! I'm Jax. I'm 3 years old."


Comparison Operators

== Equals
!= Does not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Comparison operators always return a boolean value, and are usually used in ‘if’ statements (if statements are covered in the next section).


Logical Operators

&& and
|| or
! not

Like comparison operators, logical operators always return a boolean value.

jaxIsYoung = true;
jaxIsOld   = false;
jaxIsYoung && jaxIsOld;  // false
jaxIsYoung || jaxIsOld;  // true
jaxIsYoung && !jaxIsOld; // true

Generally these are used in if statements, which are covered in the following section called ‘Conditionals’.


Increment/Decrement Operators

=+ Increment
=- Decrement
++ Increment by 1
-- Decrement by 1

These four are special because they actually modify the value of the variable.


age = 3;
// age = 4
// age = 5
age =+ 30;
// age = 35
// age = 34
age =- 31;
// age = 3

Pro Tip: All the above increment/decrement operators also return the variable’s prior value (its value before being incremented/decremented). There are also the += and -= operators, which behave the same as above but they return the variable’s new value.  Similarly, the ++ and -- can be placed before the variable reference to return the new value. The return values of these operators only matter if they are used within a greater expression; the return value is discarded if used as the entire statement, as in the examples above.



I’ll tell you a secret: conditional structures are the key to having a robust script.  Conditional structures enable multiple cases to be handled within a single script.

There are two primary types of conditional structures: if/else blocks and loops.


If/Else Blocks

An if block (or if statement) executes a block of code only if a given condition expression evaluates true.

if( jax.age < 5 ){
 jax.goTo( 'daycare' );
The condition will pass for values other than the boolean value true, which are considered “truthy”: non-empty strings, non-zero numbers, and any date, regex, object, or array (even if the object or array is empty).

An else block can be added to the end of the if block in order to execute an alternate set of code in case the expression evaluates to be false.

jax.age = 10;
if( jax.age < 5 ){
 // This code will NOT execute.
 jax.goTo( 'daycare' );
} else {
 // This code WILL execute.
 jax.goTo( 'school' );

More numerous cases can be handled by chaining a series of if/else blocks together:

if( jax.age < 5 ){
 jax.goTo( 'daycare' );
} else if( jax.age < 18 ){
 jax.goTo( 'school' );
} else if( jax.age < 60 ){
 jax.goTo( 'work' );
} else {

Pro Tip: If there are multiple possible values for a single variable that a script needs to check for, a switch statement can be simpler than a series of if statements.  Read about switch statements here.



A loop is used to run a specific set of code repeatedly until a specific condition is met.

The most common type is the for loop, which is usually used to loop through each item in an array or object.

Here is an example of looping through an array:

// nicknames = [ 'Jax', 'Jah' ];
var i, nickname;
for( i=0; i < nicknames.length; i++ ){
    // Code here will be run for
    //   each nickname.
    nickname = nicknames[i];
    say( 'Some call me '+nickname+'.' );
// Some call me Jax.
// Some call me Jah.

And an example of looping through an object:

// kid = {'age':3,'name':'Jackson'}
var attribute, value;
for( attribute in kid ){
    // Code here will be run for
    //   each attribute of 'kid'.
    value = kid[attribute];
    say( 'My' + key + ' is ' + val );

// My age is 3.
// My name is Jackson.

The other type of loop is the while loop, which is used when the number of times the loop code needs to execute is unknown (as opposed to for loops, which run code a specific number of times).

function canLiveAtHome( person ){
 if( person.age < 18 
  || person.job == "student"
  || person.paysRent ){
   return true;
 } else {
   return false;
var kid = new Person( "Jax" );
while( canLiveAtHome( kid ) ){
    // As long as canLiveAtHome() 
    //   returns true, then ...

// Once canLiveAtHome() returns
//   false, then ...



Until you are a bit more practiced at reading JavaScript, you will not remember all the concepts and syntax above.  That’s okay!  Even experienced developers have not memorized all of the names, parameters, and exact return formats of the many built-in functions.

Documentation on all of this is always a few keystrokes away in a wealth of online resources.  Simply search “javascript” and the syntax keyword or function/method name and you will find plenty of reference articles.

Often the first search result, w3schools’ articles are often high-level and non-comprehensive.  The detailed documentation on MDN (Mozilla Developer Network) is a top choice for many developers and avid learners.

You can also find lots of specific examples and answers to all sorts of issues in forums like Stack Overflow.

If you’re getting an error and you don’t know why, search for the error message verbatim to find how other people fixed it.  If you get no results, try the search without custom variable names, filenames, and line numbers.