Introduction to For Loops

Free JavaScript & jQuery Tutorial

Learn how to use JavaScript and jQuery to create a for loop and use it to set menus in this comprehensive tutorial which also includes a practical exercise.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics covered in this JavaScript & jQuery tutorial:

Creating a for loop, Using the for loop to set menus, Clearing the contents of a menu

Exercise Preview

ex prev for loops

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Overview

One of the things that programming is really good for is repeating the same (or similar) actions very quickly. In this exercise, we’ll look at one way to do this by using a for loop.

Getting Started

  1. Open your code editor if it isn’t already open.
  2. Close any files you may have open.
  3. For this exercise we’ll be working with the Volunteer-Form folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to (like Visual Studio Code does).
  4. Open index.html from the Volunteer-Form folder.
  5. Preview index.html in Chrome. (We’ll be using its DevTools later.)

    This is a mockup of a form (which doesn’t actually function). The only thing we’re going to focus on are the From/To menus.

  6. Click the menu next to From. Notice the range goes from Before 2000 to 2017.

    The To field is not selectable yet. We want to set it so that after choosing a From value, the To value only shows years equal to or later than the chosen From value.

  7. Leave the page open in Chrome so we can come back to it later.
  8. Return to index.html in your code editor.
  9. Around line 36, locate the select tag with an ID of from-year. Notice that it contains option tags which we’ve already assigned values (years) to.
  10. Around line 59, notice that the select tag with an ID of to-year is empty. For this select tag, we’ll be generating the option elements using JavaScript.

Creating a For Loop

Before we get further into this, we should take a look at what exactly loops are and how a for loop works.

  1. Around line 66, add script tags as shown in bold:

       </div>
       <script>
    
       </script>
    </body>
    
  2. Within the script tags, write a simple for loop by adding the following bold code:

    <script>
       for() {
    
       }
    </script>
    

    The () are going to take three pieces of information. Inside the {} will be the instructions that we want to execute every time the loop runs.

  3. Let’s say we want to count from 0–10. First, we need to add a counter to count how many times it’s going through the loop. Add the following bold code:

    for(var i = 0;) {
    
    }
    

    We could name the variable anything but using i is a standard convention for incrementing. We also specified that the counter starts at 0.

  4. Every time the loop runs, it will check to see if a certain condition is true. If it is true, then we need to tell it what to do… inside the {}. If it’s false, the loop will stop. Tell the loop to keep going as long as i is less than 11 by specifying the condition:

    for(var i = 0; i < 11;) {
    
  5. Finally, we’ll add the incrementer itself to specify that every time the loop runs, the value of i will increase by 1. Add:

    for(var i = 0; i < 11; i++) {
    

    NOTE: Alternately, you could write i = i + 1 or i += 1 to achieve the same results as  i++ (but with more characters).

  6. Now we need to specify what happens each time the loop runs:

    for(var i = 0; i < 11; i++) {
       console.log('The value of i is: ' + i);
    }
    
  7. Save the file.
  8. Go back to Chrome and reload index.html.
  9. If the Console isn’t open, open it by hitting Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
  10. Notice that the loop ran immediately upon page load and printed out the incrementing of i until it got to 10. Perfect!

Using the For Loop to Set Menus

How will we use for loops in the volunteer application form? When the user chooses a year in the From menu, we want the To menu to show only the years between the selected year up to the current year (nothing earlier).

  1. Switch back to index.html in your code editor.
  2. Around line 67, delete the loop we wrote:

    for(var i = 0; i < 11; i++) {
       console.log('The value of i is: ' + i);
    }
    
  3. We want to get the From and To field years and save them to variables. Type:

    <script>
       var fromYear = document.getElementById('from-year');
       var toYear = document.getElementById('to-year');
    </script>
    
  4. We need to trigger an event whenever the user changes the From menu. For now, we want to check that it’s working. Add the following bold code:

    var fromYear = document.getElementById('from-year');
    var toYear = document.getElementById('to-year');
    fromYear.onchange = function() {
       console.log(fromYear.value);
    };
    

    NOTE: We’re putting the onchange event handler directly in the JavaScript so we don’t have to add it to the HTML.

  5. Save the file.
  6. Go back to Chrome and reload index.html.
  7. Open the Console by hitting Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
  8. Choose a year in the From menu. The Console should print out the year you chose, showing that it works.
  9. Switch back to your code editor.
  10. Start the loop around line 70, replacing the console.log() line:

    fromYear.onchange = function() {
       for() {
    
       }
    };
    
  11. Start the counter with the following code:

    for(var i = fromYear.value;) {
    
    }
    
  12. Add the condition that i should be less than or equal to 2017:

    for(var i = fromYear.value; i <= 2017;) {
    
  13. Increase the value of i by 1 year:

    for(var i = fromYear.value; i <= 2017; i++) {
    
  14. Before we get any further, let’s test our for loop. Add the following bold code:

    for(var i = fromYear.value; i <= 2017; i++) {
       console.log(i);
    }
    
  15. Save the file, switch to Chrome, and reload index.html.
  16. Open the Console if it isn’t already.
  17. Choose a year in the From menu.

    In the Console you should see a list of years from the year you selected up to 2017.

  18. Choose a different year in the From menu.

    You should see a new list of years from the year you selected through 2017. The variable i is set to fromYear.value, the value you selected. Each time the loop runs, it tests to see if i is less than or equal to 2017. If it is, the loop runs. If not, the loop exits. Lastly, the i is incremented by 1 (i++) and the test is run again.

  19. Switch back to your code editor.

    Now we need to add the years we generated into the To menu. So how are we going to create everything that goes into the toYear menu? Fortunately, JavaScript lets us assemble HTML elements, give them attributes, and put content inside them.

    For each year, we want to create an option element similar to the ones around lines 37–56. We want to create a new option every time the for loop runs, give the option a value, add text, then insert it into the to-year select tag. To do that we’re going to need a variable that we can save everything in as we’re assembling it.

    Around line 69, create the option variable by adding the bold code as shown below:

    var toYear = document.getElementById('to-year');
    var option;
    fromYear.onchange = function() {
    

    NOTE: We’re not assigning the variable to anything initially, which is fine.

  20. Create the option element by replacing console.log(i); with the following code around line 72:

    fromYear.onchange = function() {
       for(var i = fromYear.value; i <= 2017; i++) {
          option = document.createElement('option');
       }
    

    NOTE: createElement() is a method that belongs to the document object. You can put whatever element you want to create within the ().

  21. Set the value attribute to the selected year:

    for(var i = fromYear.value; i <= 2017; i++) {
       option = document.createElement('option');
       option.setAttribute('value', i);
    }
    

    NOTE: Within the setAttribute() method, value is the name of the attribute we want to set. We’ll set value equal to i, which is the year currently in the loop.

  22. Next, add the textContent:

    for(var i = fromYear.value; i <= 2017; i++) {
       option = document.createElement('option');
       option.setAttribute('value', i);
       option.textContent = i;
    }
    

    NOTE: In the previous step we set the value attribute of the option tag we’re creating. In this step we’re setting the content of that option element. If i is 2012, for example, we’ll end up with something like this:

    <option value="2012">2012</option>

  23. Finally, we need a way to insert the option elements we’re creating into the to-year select tag. Let’s use the appendChild() method:

    for(var i = fromYear.value; i <= 2017; i++) {
       option = document.createElement('option');
       option.setAttribute('value', i);
       option.textContent = i;
       toYear.appendChild(option);
    }
    

    NOTE: The appendChild() method adds a child element inside a parent element at the end of a list of any other child elements that may be present.

  24. Save the file.
  25. Switch to Chrome and reload index.html.
  26. Choose a year in the From menu.
  27. Click on the To menu and notice that it only lists years starting with the selected year through 2017.
  28. Try setting a different From year.
  29. Look in the To menu and notice it doesn’t update appropriately. It keeps adding the next set of years to the end of the list without getting rid of the previous set.

Clearing the To Menu

Fortunately, we can fix this pretty easily. Each time the loop runs, we want to clear out the To menu.

  1. Switch back to your code editor.
  2. Around line 71 add the following bold code. (Note that those are two single quotes!)

    fromYear.onchange = function() {
       toYear.innerHTML = '';
       for(var i = fromYear.value; i <= 2017; i++) {
    

    NOTE: We’re using innerHTML rather than textContent because we need to change more than just the text.

  3. Save the file.
  4. Switch to Chrome and reload index.html.
  5. Choose a year in the From menu.
  6. Click on the To menu to make sure it only shows the years starting from your chosen year through 2017.
  7. Choose another year in the From menu.
  8. Click on the To menu again to see that it only shows the appropriate years. Great!

Optional Bonus: Refining the Menu Selection Experience

What we’ve done so far works, but it’s not the best user experience. For example, say the user has chosen a From and To date, but then needs to change just the From date again. When they do that, the To date will automatically reset, requiring them to set it again.

This functionality is acceptable only if the user accidentally chooses a starting year (From year) that is later than the end of their volunteer experience (the To year). In all other cases, we need to make sure the chosen To year stays constant. We’ll remember the To menu’s value by storing it in a variable. We can then use that saved value to reset the To menu after the From menu has changed.

  1. Switch back to index.html in your code editor.
  2. Around line 69, declare a variable for the value of the To year menu:

    var option;
    var toYearVal;
    fromYear.onchange = function() {
    
  3. Let’s store the user’s original To year value before we clear it out. Add the following bold code:

    fromYear.onchange = function() {
       toYearVal = toYear.value;
       toYear.innerHTML = '';
    
  4. After the loop is done running, let’s first look to see if the To year value is greater than or equal to the starting point of the From year. Around line 79, add:

          toYear.appendChild(option);
       }
       if(toYearVal >= fromYear.value) {
    
       }
    };
    
  5. If the To year value is greater than or equal to the From year value, we want to make sure the original To year value remains unchanged. We can use the value we stored from the user’s initial selection to make sure of that. Add the bold code shown below:

    if(toYearVal >= fromYear.value) {
       toYear.value = toYearVal;
    }
    
  6. Save the file.
  7. Reload index.html in Chrome.
  8. Click on the From menu and choose a year.
  9. Click on the To menu and choose a year.
  10. Go into the From menu again and change it to an earlier year.
  11. Notice the To menu should still have the same year you selected before.
  12. Click on the To menu to see that the year range has been updated to start from the currently selected From year.
  13. In the From menu, choose a year that is later than the current To year. You should see the To year update to the later year.

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Volunteer-Form.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram