Tuesday, February 18, 2014

Beginner's Guide to Javascript You Should Know For AdWords Scripts

I've heard from a few readers that the posts on this blog have inspired them to learn to code. That's awesome! But I've also heard from a few that say they have run into trouble getting through many of the Javascript tutorials out there since they deal mostly with Javascript for web design or Node.js.

So this post is going to attempt to get someone up to speed with Javascript enough that they can at least walk through most of the code I post here and make changes when needed. Also, I aim to at least help you know what to Google when you get stuck.

A few caveats. Is this meant to be a replacement for a full coding class? No. Will I be making generalizations and over-simplifying some extremely complex topics? Yes. Are there mistakes in this? Probably. If you find one, let me know.

* Intro to Javascript For AdWords Scripts
* Version 1.0
* Created By: Russ Savage
* FreeAdWordsScripts.com
function main() {
  // This is a comment. AdWords Scripts ignores this
  /* Here is another way to comment
     that can be used when you need
     to comment multiple lines */
  // The main function tells AdWords where to start. You always need
  // at least a main function in your script.
  // Let's start with some variables (or primatives)
  // More info on Javascript variables can be found:
  // http://www.tutorialspoint.com/javascript/javascript_variables.htm
  var clubName = 'Fight Club'; // declared with single quotes
  var rule1 = "Don't talk about fight club."; // or double quotes if needed
  var members = 12; // a number, no quotes
  var dues = 3.50; // also a number
  var isAcceptingNewMembers = true; // a boolean, for yes or no answers
  // When you need to store multiple values, consider an Array
  // More detailed intro to Arrays can be found here:
  // http://www.w3schools.com/js/js_obj_array.asp
  var memberNames = ['brad','edward','robert'];
  // Which you can access the values with an index
  var coolestMember = memberNames[0]; // pronounced member names sub zero
  // 0 is the index of the first element of the array, 1 for the second, etc.
  // We can use the length property of an array to find out how big it is.
  var numberOfMembers = memberNames.length; // this will be 3
  var dailyFights = numberOfMembers*2; // star ( * ) is an operator for multiply
  // so the total number of fights is 6.
  // More on operators can be found here:
  // http://web.eecs.umich.edu/~bartlett/jsops.html
  // If you want to group multiple variables together, you can using an Object.
  // An Object is simply a grouping of common variables (and other stuff we'll see later)
  var FightClub = { // The curly brace says group these things together. there is another one at the end.
    clubName : 'The Fight Club', // a string variable. In an Object, we use : instead of = for assignment
    rules : ["Don't talk about fight club.",  // each variable is separated by a comma, instead of a semi-colon
             'Do not talk about fight club.'],
    memberNames : ['brad','eddy','robert','phil','dave'],
    dues : 3.50, 
    foundedYear : 1999
  // Now to access the variables inside the object, we use the dot
  Logger.log(FightClub.clubName); // prints The Fight Club
  Logger.log(FightClub.memberNames[0]); // prints brad
  // Objects are one of the most important concepts of Javascript and they will come back
  // again and again a little later. More details can be found here:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
  // Sidebar: Why do I use camelCase for variable names? Technically
  // I could 
  var UsEWhaTevERIwanteD = 'but camelCase is easier to read';
  // and conforms to the style guide that Google recommends:
  // https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Naming
  // Follow the style guide. It helps others read your code.
  // If statements (or control statements) allow you to split your code path if needed
  if(numberOfMembers > 10) { // if we have more than 10 members
    dues += 1.00; // increase the dues, 
    // plus equals (+=) says "add the value on the right to the value on the left"
  } else { // otherwise
    dues -= 1.00; // decrease the dues
    // there are also -=, *= (multiply), /= (divide by), and %= (modulo equals)
  // Comparison operators like >, <, ==, ===, <=, >= allow you to compare values
  // They return true or false, always
  // Notice the double and triple equal signs. That's not a typo. More info can be found at:
  // http://www.impressivewebs.com/why-use-triple-equals-javascipt/
  // You can also have multiple if statements and multiple things to test
  if(dues > 5) { // if dues are over $5
    dailyFights++; // increase the fights
  } else if(dues > 2 && dues <= 5) { // if dues are greater than $2, but less than $5
    dailyFights--; // decrease the fights
  } else { // otherwise
    dailyFights = numberOfMembers*2; // reset the fights
  // You'll probably notice none of this makes sense. it is only for example.
  // Double Ampersand && just means AND, || means OR. So in the statement above,
  // both statements with operators must be true in order for the fights to be decreased.
  // Oh, and ++, -- is shortcut for +=1 and -=1 respectively.
  // Ok, now lets talk about loops. 
  // Here are a few different ways to loop through the members
  // This is called a While Loop and while it might be easy to understand,
  // You won't use it nearly as often as the other two.
  var i = 0; // the variable i is what we will use for each indice
  while(i < memberNames.length) { // while i is less than the length of names
    Logger.log(memberNames[i]); // print out the name
    i++; // and increment the index by 1
  // i is a variable that controls the loop. A common issue with While loops
  // is that you will forget to increment the loop control and you get an infinate loop
  // This is the classic For loop
  // The declaration, checking, and incrementing are all done 
  // in the first line so it is harder to miss them
  for(var index = 0; index < memberNames.length; index++) {
  // And finally, the easiest loop but hardest to explain, the ForEach loop
  // This is just a variation of the For loop that handles incrementing index
  // behind the scenes so you don't have to.
  for(var index in memberNames) { // declare index, which will be assigned each indice
    Logger.log(memberNames[index]); // Use the indice to print each name
  // You can jump out of a loop before it reaches the end by combining the if statement
  for(var index in memberNames) { 
    if(memberNames[index] === 'edward') {
      break; // break is a keyword you can use to break out of the loop.
  // In this case, only the first name is printed because we broke out once we had the 
  // second name. More on break and its partner, continue, check out:
  // http://www.tutorialspoint.com/javascript/javascript_loop_control.htm
  // Now let's talk about functions. We have already seen a function in action: main()
  // Functions are groupings of useful code that you can call over and over again easily
  function fight(player1, player2) {
    if(Math.random() < .5) {
      return player1;
    } else {
      return player2; // return means we are going to send player2 back 
                      // to the code that called the function
  // This code can be called over and over again using a loop
  for(var player1 in memberNames) { // Loop through each member
    for(var player2 in memberNames) { // Then loop through again 
      if(player1 !== player2) { // Players can't fight themselves so check for that
        Logger.log(fight(player1,player2)); // Then call the function we defined earlier
  // This code calls fight() for:
  //    brad vs. edward, brad vs. robert
  //    edward vs. brad, edward vs. robert
  //    robert vs. brad, robert vs. edward
  // Some other functions we have been calling are Logger.log() and Math.random()
  // The cool thing is that as callers of the function, we only need to know how
  // to call the function, we don't need to know how it works behind the scenes
  // For example:
  //   var answer = LargeHadronColider.simulateEleventhDimensionalQuantumThingy(47);
  // Who knows how this works. All we need to know is to send it a number and expect a
  // number back.
  // I hope you've been noticing all of the Objects we have been using here. Logger is one,
  // Math is another one (and LargeHadronColider is a fake one). Along with variables, we 
  // can also put functions in there as well:
  var FightClub = { 
    // ... all that other stuff
    chant : function() { 
      Logger.log('His name is Robert Paulson.'); 
    totalMembers : 5
  // Whoa trippy. So what happens when I call 
  // It's going to print His name is Robert Paulson
  // The thing that makes Google AdWords Scripts different from writing just regular Javascript
  // is all of the pre-defined Objects that use functions to interact with AdWords.
  // How does the above statement work?
  AdWordsApp  // this is a predefined object in AdWords Scripts
    .keywords() // which has a function called keywords() that returns a KeywordSelector object
    .withLimit(10) // which has a function withLimit() that returns the same KeywordSelector object
    .get(); // which has a function get() that returns a KeywordIterator object.
  // Check out the AdWords Scripts documentation to find the objects and classes that make up these calls
  // https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp
  // https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp#keywords_0
  // https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_keywordselector
  // https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_keywordselector#withLimit_1
  // https://developers.google.com/adwords/scripts/docs/reference/adwordsapp/adwordsapp_keywordselector#get_0
  // So I think that just about does it for this tutorial.  If you made it this far, awesome! Post a comment to ask
  // any questions you might have.
  // Thanks,
  // Russ


  1. Hello to all of you, thanks for landing on the TutorialPath.com, which is “Your Path to Learn Everything” in an easy way and you can learn almost every sort of important elements about online things.

  2. how can be run this scripts in our source code??

  3. Hello to all of you, thanks for landing on the TutorialPath.com, which is “Your Path to Learn Everything” in an easy way and you can learn almost every sort of important elements about online things.

  4. thanks for your details it's very useful and amazing.your article is very nice and excellentweb design company in velachery


  5. awesome blog it's very nice and useful i got many more information it's really nice i like your blog styleweb design company in velachery

  6. I thought protecting the website from the hackers is a hectic task. This post makes it easy for the developers and business people to protect the website. Keep sharing posts like this…
    Smarty Developers
    Hire Dedicated Magento Developer
    Hire Dedicated Web Developers
    Dedicated Wordpress Developer
    Hire Dedicated Php Developer

  7. Awesome post. I am a normal visitor of your blog and appreciate you taking the time to maintain the excellent site. I’ll be a frequent visitor for a long time.

    ACP Sheet
    ACP Sheet Price
    Aluminium Composite Panel
    ACP Panel
    ACP Sheets

  8. Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.
    tree service near me in palm beach county

  9. Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading.
    water heater replacement nashville

  10. Hi, This is nice article you shared great information i have read it thanks for giving such a wonderful Blog for reader.
    air conditioning repair royal palm beach

  11. I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it..
    pest control companies royal palm beach florida

  12. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place. nashville remodeling contractors

  13. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.
    bathroom remodelers albuquerque

  14. I think this is one of the most significant information for me. And i’m glad reading your article. empire pest control wellington fl

  15. Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.
    bathroom remodeling maricopa county

  16. Great article and a nice way to promote online. I’m satisfied with the information that you provided hvac repair palm beach county

  17. Hello Admin!

    Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai / Printing in Chennai , Visit us now..

  18. Get the best economics assignment writing help online at essaycorp.com.au. 100 % Trusted & Secure. We offer economics assignment & homework help On-time Delivery and Affordable Price.
    Economics Assignment Help

  19. Great blog, thank you so much for sharing with us. Get a custom mobile app development services at Appslure WebSolution by the professional ios app designers and developers and also get e-commerce app Services
    App development company in mumbai

  20. Good job! Fruitful article. I like this very much. It is very useful for my research. It shows your interest in this topic very well. I hope you will post some more information about the software. Please keep sharing!!
    SEO Training in Bangalore
    SEO Course in Bangalore
    SEO Training Institute in Bangalore
    Best SEO Training Institute in Bangalore
    SEO Training Bangalore

  21. Thanks for sharing it. Love your content!
    Keep up the good work! Will definitely follow it up…
    Order now marlboros at best price you can find…

  22. just read out the whole post. The post is wonderful and inspire to the reader.. Thank you
    Do my homework quickly


  23. You write this post very carefully I think, which is easily understandable to me. Not only this, but another post is also good. As a newbie, this info is really helpful for me. Thanks to you.
    Tally ERP 9 Training
    tally classes
    Tally Training institute in Chennai
    Tally course in Chennai

  24. Great efforts put to publish these kinds of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create great relations. You’re doing an excellent job. Keep it up.

    Magento Development Training Course in Chennai Zuan Education

    Selenium Training Course in Chennai Zuan Education

  25. Really informative blog for all people. Thanks for sharing it...
    PHP Training in Bangalore

  26. Informative blog. Your blog is really helpful...Railway Recruitment 2020 is one of the major and largest government sectors. Every year, thousands and lakhs of freshers whether graduates or post-graduates are looking for Railway Jobs...

  27. GST Registration

    This tax came into applied in India July 1, 2017 through the multiple Amendment of the Constitution of India. The GST replaced existing many Central and State Government taxes.

    This article is really helpful to you, Every business and offices required GST Registration in Delhi and GST Registration in Gurgaon. We also provide professional service for gst return, gst guidanace, gst certificate download as well as we provide GST Registration in Noida and GST Registration in Bangalore.

    Get complete detail about gst registration, GST registration status, gst procedure, gst number, gst guide. GST experts in India provided by yourdoorstep will assist you through the entireprocess. Online GST Registration File your GST application & get your GSTIN number Online. Agents and consultanst at yourdoorstep help you to get GST Registration done online in 3 hours without any problem.

    Our GST Colsultants also available for gst registration in chandigarh, gst registration in faridabad, gst registration in mumbai and gst registration in ahmedabad.

    We are best in gst services, duplicate gst certificate, gst renewal n etc

  28. Awesome post! This is helpful post. Article is very clear and with lots of useful information. Thanks for such nice article
    Visit : https://pythontraining.dzone.co.in/training/data-science-training.html

  29. Our mission is to provide affordable digital marketing services & Seo Services With Google Ranking service. We provide professional and complete customer satisfaction services at competitive prices.

  30. It's very useful blog post with inforamtive and insightful content and i had good experience with this information. We, at the CRS info solutions ,help candidates in acquiring certificates, master interview questions, and prepare brilliant resumes.Find top Salesforce admin interview questions in 2020.
    These Salesforce developer interview questions are highly helpful in 2020. You can read these Salesforce lightning interview questions and Salesforce integration interview questions which are prepared by industry experts.

  31. Such a very useful article. Very interesting to read this article. I would like to thank you for the efforts you had made for writing this awesome article.
    Data Science Course in Pune
    Data Science Training in Pune

  32. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
    Data Analytics Course in Pune
    Data Analytics Training in Pune

  33. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    Business Analytics Course in Pune
    Business Analytics Training in Pune

  34. DigiPeek Provide Domain Rating & Domain Authority Increasing Service. DR 70+ & DA 50+ With Money Back Guaranteed.

    Grab your Ahrefs Domain Rating 70+ & Moz Domain Authority 50+ here!

    Does domain authority matter?

    Yes, Your Domain Authority is important because it is representative of how you rank on search engine. It helps you better understand your site's credibility in the eyes of the search engines and you can see how you compare to your competition.

    Thank you!

  35. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
    Ethical Hacking Course in Bangalore
    Certified Ethical Hacker Course

  36. Thumbs up guys your doing a really good job. It is the intent to provide valuable information and best practices, including an understanding of the regulatory process.
    Cyber Security Course in Bangalore

  37. Very nice blog and articles. I am really very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post.
    Cyber Security Training in Bangalore

  38. I will really appreciate the writer's choice for choosing this excellent article appropriate to my matter. Here is deep description about the article matter which helped me more.
    Best Institute for Cyber Security in Bangalore

  39. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    Best Data Science Courses in Bangalore

  40. everyone want to more about this so you can Click here to find more in very deep details

  41. Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

    Forex Signals Forex Strategies Forex Indicators Forex News Forex World

  42. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
    Ethical Hacking Course in Bangalore

  43. Wow! Such an amazing and helpful post this is. I really really love it. I hope that you continue to do your work like this in the future also.
    Ethical Hacking Training in Bangalore

  44. Never too late to start learning at Salesforce Training in Australia even though you don't have any programming knowledge you can excell in Salesforce Training in London United Kingdom (UK) because it is all about your customers, so this time find the best Salesforce Training in Europe. This way we will learn Salesforce CRM.

  45. I am impressed by the information that you have on this blog. Thanks for Sharing
    Ethical Hacking in Bangalore

  46. Myself so glad to establish your blog entry since it's actually quite instructive. If it's not too much trouble continue composing this sort of web journal and I normally visit this blog. Examine my administrations.
    Go through these Salesforce Lightning Features course. Found this Salesforce CRM Using Apex And Visualforce Training worth joining. Enroll for SalesForce CRM Integration Training Program and practice well. 

  47. best jewellery shop in chennai

    The craze on jewelry never goes down. Are you looking for the best Jewellery shops in Chennai? Here, is the list for you.