Java Script For Google Ads

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Arrays

A data structure used to store a list of items Multiple types can be used in an array like numbers and strings Each element in an array has an index An Array is an object in JavaScript and can be used with the . notation

Method

A function that is part of an object. The function is defined in an object.. Example AdsApp.keywordSelector() - Returns the selector of all keywords in the account (The above example would be calling the keywordSelector method of the AdsApp Object) Object: AdsApp Method: keywordSelector()

Variable

A variable is a named reference to a value. A variable is created with the JavaScript reserved keyword "var", and can be assigned a value using the equals sign. Example: var age = 3;

\n

Adds a new line to a string

Best practice for naming variables

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.

Arrays

An array is an ordered collection of values. an ordered collection of values. 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. Example: nicknames = [ 'Jax', 'Jah', 'Jay' ]; nicknames[0]; // 'Jax' nicknames[1]; // 'Jah' nicknames[2]; // 'Jay'

Creating an object

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. Example: var kid = {'age':3,'name':'Jackson'};

A complex object (not a formal term)

An variable which has one or more keys with containing keys each with their own values. Example: var kids = { 'firstborn' : { 'name' : 'Jackson', 'age' : 3 }, 'middleChild' : { 'name' : 'Jazmine', 'age' : -0.65 }, 'theBaby' : { 'name' : 'Isaiah', 'age' : undefined } }; Example of how to access complex objects kids.firstborn.age; // 3 kids.theBaby.name; // 'Isaiah'

An array can be used instead of an object

Any given dataset can be represented by either an array or an object. var kids = [ { 'name' : 'Jackson', 'age' : 3 }, { 'name' : 'Jazmine', 'age' : -0.65 }, { 'name' : 'Isaiah', 'age' : undefined } ];

What is an iterable Object in JavaScript? (An object that can be used with an Iterator)

Any object created with an Array

Core - Google Ads Scripts

Are Central objects accessed through the AdsApp. Each of these are objects, and each of them have corresponding Selector and Iterator objects to allow accessing those Entities. Examples: Account Ad AdGroup AdGroupCallout AdGroupReview AdGroupSitelink AdParam AdSchedule Keywords Campaign Label Additional examples: AdSchedule Audience BiddingStrategy Budget Callout Campaign CampaignCallout CampaignReview CampaignSitelink DisplayKeyword ExcludedAudience MobileApp NegativeKeyword PhoneNumber Placement Platform ProductAd ProductGroup Review ShoppingAdGroup ShoppingCampaign Sitelink Topic

Google App Objects

Are built-in global objects that make it easy to interact with a few Google platforms. -AdsApp -SpreadsheetApp -MailApp

arguments

Are parameters or input variables that effect the output of the function Example: function whoAmI( name ){ return "I'm " + name + "!"; } whoAmI( "Jax" ); // "I'm Jax!" // in the above example "name" is the argument

Selectors — google ads

Are used to retrieve a list of specific Entities. Each Entity has its own type of Selector. Some Entity Selectors are accessed directly from the AdWordsApp object, and others are accessed using methods in the Entity that contains them. Example: keyword.getStatsFor("THIS_MONTH")

Operators in JavaScript

Arithmetic Assignment Comparison Logical Bitwise

Lose equality Operator

Automatically converts the right side of the expression to match the value type of the left so only the value needs to match. Indicated by ==

Arithmetic Operators

Basic Addition X + y Subtraction X-y Division x/y Reminder X %Y Exponent x**y Increment: ++x or x++ Decrement: —x or x—

Types of values in JavaScript

Boolean Number String Regex Date And two complex types, which can contain multiple values: Array Object

The result of an expression that contains a comparison Operator is what value?

Boolean (true or False)

Alternative use case for comments

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.

Configuration settings in pre-built scripts

Configuration settings are the variables named with all-caps, listed after the metadata comment at the top of the script.

var

Creates a variable in JavaScript.

An Object litteral

Curly braces used to define an object. = { name: 'mosh', age: 30 }; Note: a comma needs to be after each key property except for the last one

How to add to an Array

Example selectedColors[2] = 'green'; console.log(selectedColors);

For loop

Example code: For (condition){ Statement } for (let I = 0; i <= 5; I++) { if (i % 2 !==0) console.log(i); } In loops i is often used to stand for index Variables in loop are different from variables outside the for loop

Ternary Operator

Example: Let type = points > 100 ? 'Gold' : 'Silver'; In the expression above type will equal gold if the value of points is greater than 100 but will equal silver if the value of points is less than 100

Switch Case

Executes code based on the variable. Can also be used with if and else statements Var role = 'guest'; Switch(role){ Case 'guest': Console.log ('guest user'); Break; Default: Console.log('unknown user');

Types of Loops in JavaScript

For While Do...while For...in For...of They all essentially do the same thing: repeat an action a number of times

Key value pairs

Form the properties of an object

How functions are called

Functions are called using the function name, followed by a set of parentheses: Example: makeItRain()

infinite loop example

Happens if programmed incorrectly. Can crash your computer or browser. Let i = 0; While (I < 5) { console.log(i); } Forgetting to increment i means this loop will run forever

Dot Notation .

How you access or change the key value pairs of a property in an object Example: Person.name = "john"; In the above example you are changing the key value pair for the property of name to John

Built-in functions

If you can see a function, but can't see a function definition, then it is a built-in function. These work exactly the same way as custom functions. Google Ads has a number of built in functions

Two types of conditional statements in JavaScript

If...else Switch...case

number values in JavaScript vs. other languages

In JavaScript you don't have floating point number and integers, just the primitive value of number

Whitespace 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.

While loops vs do while loops

In while loops the condition is evaluated at the start and the statement will not run unless the condition is true In do while loops the statement always runs at least once even if the statement is false, because the condition is checked at the end

Template literals

Indicated by back comma notation. Allows you to format things normally with spaces and characters. Was part of the ES6 update. Can be dynamically updated with values using place holder values ${name} to pass values into the expression

//

Indicates a comment.

AdsApp

Is central to any Google Ads script, providing read and write access to AdWords configurations and report data. You'll learn more about it in the next section. Each object is distinguished by its intended use. In Google's documentation, these uses are identified by these terms: Entity - central objects Selector - used to select existing Entities Iterator - used to loop through and access each selected Entity Builder - used to create new Entities

What are Google Ads Scripts

JavaScript, imbued with some Google Ads concepts and libraries.

object literal syntax

Let p1 = { name: "Steve" };

Chaining

Methods that can be called one after another Best practice for chaining is to put each new method on a new line Numbers

New Operator in Constructor Functions

New Operator must be used when creating a new object with a constructor function

Value Types

Number String Boolean Symbol Undefined Null

Reference Value Type

Object Array Function

Use case for objects in JavaScript

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).

Google Ads entities

Objects with corresponding Selector and Iterator objects

Best Practice with Line Breaks for declaring a variable

Only declare one variable per line var dad = "Tom"; var brother = "Gabe";

Logical AND

Operator : && Returns a true if both operands are true

Best practice when changing a pice of code

Particularly for optional settings, it's a good idea to leave a comment with the date, your email, and an explanation of why you changed the setting. It might seem unnecessary, but trust us, later you (or someone else) will be really glad you did.

Reference Types

Primitive: Number String Boolean Symbol Undefined Reference types: Object Function Array

Factory Functions

Produces objects. Used if objects have logic so long code doesn't need to be repeated. Created by placing the definition of an object inside a function camelNotation is used for the naming convention Example: Function createCrircle(radius){ return { radius, draw() { console.log('draw'); } }; }

Comparison operators

Relational > < <= >= Equality Equal to (strict equality operator) === Equal to (lose equality operator) == Not equal to !==

keyword.getStats

Returns stats for the specified date range. Supported values: TODAY, YESTERDAY, LAST_7_DAYS, THIS_WEEK_SUN_TODAY, LAST_WEEK, LAST_14_DAYS, LAST_30_DAYS, LAST_BUSINESS_WEEK, LAST_WEEK_SUN_SAT, THIS_MONTH, LAST_MONTH, ALL_TIME.

Logical OR

Returns true if one of the opperands is true Operator: (||)

Why use selector conditions

Selector conditions are optional, but using Selectors without conditions can cause your script to run much more slowly than necessary. It may be easier to select all instances of a particular Entity, then act conditionally based on specific parameters later in the script, but it's worthwhile to use Selector conditions instead.

An expression in JavaScript

Something that produces a value

Order by Method keywords

Specifies the order of the resulting entities orderBy("meterics.clicks DESC"); .orderBy("meterics.clicks ASC") .orderBy("meterics.ctr ASC")

Primitive Value Types

Strings Number Boolean Undefined Null

Argument of a function

The exact value passed through the parameter of a function greet('John'); John is an argument of the greet function

The includes Method

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. Syntax array.includes(element, start) Parameters Parameter Element: Required - The value to search for. Start: Optional - Start position. Default is 0.

Bracket notation

The other way to change or access specific properties of an object Person['name'] = 'John' Best practice is to use the dot notation because it's cleaner

Object

The same as variables in JavaScript, the only difference is that an object holds multiple values in terms of properties and methods

Parameter of a function

The text inside the parentheses of a function when defining function. The input for a function. function greet(name) { console.log('hello' + name); } Name is a parameter of the greet function A function can have multiple parameters by using a comma to separate the parameters

For-in Loop Example

The used to iterate over the properties of an object Const = person = { name = 'mosh' age = 'age' }; for (let key in person) console.log(key, person[key]);

Strict Equality Operator

The value type and Value must be the same Indicated by ===

Boolean

There are two boolean values: true and false. var jaxIsYoung = true; var jaxIsOld = false;

Defining a function

To define, add a left facing curly brace after the parentheses, write the code and close the code with a ; and right facing curly brace. // Assign code to the function name: 'makeItRain'. function makeItRain(){ // Code to make it rain goes here. } Full example: function addTwoAndThree() { return 2 + 3; }

How to define a function

Use the function keyword function = greet( ) { {

Spread Operator

Used to create a duplicate array Example: Const = [...array];

Splice Method

Used to remove an element from an array Example use: output.splice(1, 0) (index of 1, delete 1 item)

Constructor Functions

Uses PascalNotation: every word is upper case Used if objects have logic so long code doesn't need to be repeated.

Constructer Function

Using the this keyword along with the new operator function Circle(radius) { this.radius = radius; this.draw = function() { console.log ("draw"); } }

Naming variables

Variables should always be named with a lowercase letter. This will help avoid conflicts with most built in variables which generally start with uppercase letters. Capitalize the first letter of each subsequent word. Using lowerCamelCase

Difference between while loop and for loop

You declare the variable externally of the loop. let i = 0; While ( i <= 5) { if (i % 2 !==0) console.log(i) i++; }

Array literal

[ ]; indicates an empty array

Functions in JavaScript

a reusable piece of code, like a sub-script within the script.. Can be called repeatedly—and every time it's called, the function code re-runs. 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).

JavaScript Statements and Punctuation

an instruction. 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. Example: sentences=text.split('. ');

How to access a objects items

can be accessed can also be accessed using dot notation or brackets Example: kid.age; // 3 kid.name; // 'Jackson' kid['age']; // 3 kid['name']; // 'Jackson'

Numbers

can be written as integers, decimals, or in exponential form. var age = 3; var pi = 3.14159; var leagues = 2e4; // 20,000

Selector conditions

conditions that filter and sort the list of retrieved Entities Selectors for various Entities may have unique condition methods specific to that Entity, but most Selectors have a few core condition methods: withIds() forDateRange() orderBy() withLimit() withCondition()

If...else

if (condition) { statement } else if (anotherCondition) { } If you have multiple statements you need to use curly braces Else Statement

Parameters

input variables for functions

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. only year and month are required; the date need only be set to the specificity needed by the script. 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 birthday = new Date( 2013, 4, 4 ); // May 4, 2013 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();

Objects

is an unordered collection of key/value pairs. Remember objects can have specific functions

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!";

global object

object is at the top of the scope chain and that its properties and methods are effectively global variables and global functions Google Ads example: -App Objects -Utility Objects

block comments

start with /* and end with */ and can span multiple lines

useful string methods.

trim() strips leading and trailing whitespace. Example: greeting = " hi "; greeting.trim(); // "hi" —————— toLowerCase() and toUpperCase() convert all characters to a single case. Example: greeting = "Hello!"; greeting.toLowerCase(); // "hello!" greeting.toUpperCase(); // "HELLO!"

Assignments Operators

var Let Addition assignment operator x += 5 Means X = X +5 Multiplication assignment operator x*=5 Means x = x * 5


Ensembles d'études connexes

Chapter 13: The Molecular Basis of Inheritance

View Set

BL Linux - Ch. 19 Networking Fundamentals

View Set

Chp 24 Making the Transition from Student to Professional Nurse

View Set

ATI Exam 1 (Renal, Oncology, Neuro)

View Set

Explaining total cost, variable cost, fixed cost, marginal cost, and average total cost for Econ. 1

View Set