For Loops: Free JavaScript Tutorial

Discover how to effectively use JavaScript 'for loops' through our comprehensive tutorial that covers creating and using a 'for loop' and applying it in a product chooser.

This exercise is excerpted from Noble Desktop’s JavaScript for Front-End training materials and is compatible with JavaScript updates through 2023. To learn current skills in JavaScript with hands-on training, check out our Front-End Web Development Certificate, Full-Stack Web Development Certificate, and coding classes in-person and live online.

Topics Covered in This JavaScript Tutorial:

Creating a for Loop, Using the for Loop to Set Menus, the JavaScript Keyword This, Using a for Loop in the Product Chooser

Exercise Preview

preview loops

Exercise Overview

In this exercise, you’ll learn how for loops are useful for repeating the some code multiple times.

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

Getting Started

  1. For the first part of this exercise we’ll be working with the Loops folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  2. In your code editor, open index.html from the Loops folder.
  3. Preview index.html in Chrome. (We’ll be using its DevTools.)

    Notice this is a blank page. We don’t actually need any page content because we’ll be using the Console.

  4. Leave this page open in the browser, so you can reload it later.

Creating a for Loop

  1. We’ve already added a script tag. In it, start writing a for loop by adding the following bold code:

    <script>
       for() {
    
       }
    </script>
    • In the () we’ll add 3 pieces of code controlling the loop.
    • In the {} we’ll add the code we want to execute every time the loop runs.
  2. 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(let 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.

  3. 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(let i = 0; i < 11;) {
  4. 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(let 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).

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

    for(let i = 0; i < 11; i++) {
       console.log('The value of i is: ' + i);
    }
  6. Save the file and reload the page in Chrome.
  7. Open the Console by hitting Cmd–Opt–J (Mac) or CTRL–Shift–J (Windows).
  8. Notice that the loop ran immediately upon page load and printed out the incrementing of i until it got to 10. Perfect!
  9. We’re done with this page, so close the browser window.

Using a for Loop in the Product Chooser

  1. In your code editor, close any files you may have open.
  2. For the rest of this exercise we’ll be working with the Product-Chooser-Loops folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  3. In your code editor, open product.html from the Product-Chooser-Loops folder.
  4. Preview product.html in Chrome.

    This file is where we left off in a previous exercise for this project. When you click the red button it changes the photo and the button gets an black border, but we want all buttons to have this same functionality.

    All the buttons have a class of swatch. Let’s get all the buttons (which will be an array), and loop over them (adding an event listener to each one).

  5. Back in your code editor, add an s to colorButton to make it plural:

    let colorButtons = document.getElementById('red');
  6. Change getElementById to querySelectorAll:

    let colorButtons = document.querySelectorAll('red');

    NOTE: querySelectorAll() accepts values like you’d use when targeting elements with CSS selectors, as you’ll see next. It finds all of the elements, so you’ll get an array instead of a single element as we get with getElementById().

  7. Change red to the .swatch class (which all the buttons have in common):

    let colorButtons = document.querySelectorAll('.swatch');
  8. Now that we have an array of all the buttons, we need to loop over them, adding an event listener to each button. Wrap a loop around the addEventListener:

    }
       for(i = 0; i < colorButtons.length; i++) {
          colorButton.addEventListener('click', changeColor);
       }
    </script>
  9. Our addEventListener code is still targeting the single button we had set up. Now that we’re using querySelectorAll it will find all the elements with a class of swatch, so we’re getting an array.

    As we loop over each button, we’ll want to target the specific button using the index of our loop. Add s[i] as shown below, being sure not to miss the adding an s to colorButton to make it plural:

    for(i = 0; i < colorButtons.length; i++) {
       colorButtons[i].addEventListener('click', changeColor);
    }
  10. Save the file and reload the page in Chrome.

    • Click the yellow button to see it changes the image (we know it’s to the wrong red image, but we’ll fix that next).
    • Reload the page.
    • Click the blue button to see it also changes the image (again we know it’s the wrong red image, but we’ll fix that next).
    • We’ve successfully made each button change the image (when we started only one button worked). What’s left is to make each button set the correct color image, and to add the border around the button being clicked.

Targeting the Current Element

We need to look at the specific individual element being clicked so we can grab it’s ID for the color, and use that to change the image to the appropriate image.

  1. Back in your code editor, in the changeColor() function, add the following:

    function changeColor() {
       console.log(this);
       productPhoto.src = 'img/chair-red.jpg';
       colorButton.classList.add('selected');

    The JavaScript Keyword This

    In JavaScript, we use the keyword this much the way we use the “this” in everyday natural language. In JS (as in natural language) you must be careful to think about how “this” is determined. In the global context (outside of any function), this refers to the global object, but an event property is owned by the HTML element it belongs to, therefore in that context this refers to the HTML element. You can learn more about the JS keyword this at tinyurl.com/javascript-keyword-this

  2. Temporarily comment out the colorButton line because that will create an error now that we changed that variable to colorButtons (plural).

    function changeColor() {
       console.log(this);
       productPhoto.src = 'img/chair-red.jpg';
       // colorButton.classList.add('selected');
  3. Save the file and reload the page in Chrome.
  4. Open the Console by hitting Cmd–Opt–J (Mac) or CTRL–Shift–J (Windows).

    Click each button and in the Console see it’s outputting the button you’re clicking!

    Notice the ID of each button is their color. We’ll need that to know which image src to use. Let’s get that programmatically.

  5. Back in your code editor, add .id after this:

    console.log(this.id);
  6. Save the file and reload the page in Chrome.

    Click each of the buttons and in the Console see it’s outputting the color of the button you’re clicking.

  7. Now that we know how to get the current color, we need to use that the grab the correct image. Back in your code editor, replace red with the following bold code:

    function changeColor() {
       console.log(this.id);
       productPhoto.src = 'img/chair-' + this.id + '.jpg';
  8. Save the file and reload the page in Chrome.

    Click each button and notice the image changes to the correct color photo. Nice!

    We’ll almost done. We also need change the class of the button that’s being clicked, so the user will know which color is currently selected.

  9. Back in your code editor, remove the comment from the beginning of the line, and replace colorButton with this

    function changeColor() {
       console.log(this.id);
       productPhoto.src = 'img/chair-' + this.id + '.jpg';
       this.classList.add('selected');
    }
  10. Save the file and reload the page in Chrome.

    • Click the blue button.

      Notice the image changes to the correct blue photo, and the blue button gets a black border. Perfect.

    • Click the yellow button.

      The images changes to the correct photo, and the yellow button gets its border. Those are all great, but the other buttons still have their black border.

      We’ll have to remove the borders from all the other buttons before adding the border to the button that is clicked. Because we won’t know which other button has the border, we’ll loop over them all and remove the class from all of them.

  11. Back in your code editor, add the following loop:

    function changeColor() {
       console.log(this.id);
       productPhoto.src = 'img/chair-' + this.id + '.jpg';
    
       for(i = 0; i < colorButtons.length; i++) {
          colorButtons[i].classList.remove('selected');
       }
       this.classList.add('selected');
    }
  12. Save the file and reload the page in Chrome.

    Test out all 4 buttons and everything should work perfectly: each button you click should get a black border around it, and change the photo to the appropriate color. Only one button should ever have the black border.

  13. Back in your code editor, delete the console.log(this.id) line of code.

    You should never leave Console logging in your final code that you’ll use.

Optional Bonus: Changing the Click Event to Hover

The product photo changes when the user clicks a button, but what if we wanted it to happen on hover?

  1. Back in your code editor, change click to mouseover:

    colorButtons[i].addEventListener('mouseover', changeColor);
  2. Save the file and reload the page in Chrome.

    Hover over the color swatches and see you no longer need to click. On mobile devices which don’t have the ability to hover, users can tap and it will still work.

photo of Dan Rodney

Dan Rodney

Dan Rodney has been a designer and web developer for over 20 years. He creates coursework for Noble Desktop and teaches classes. In his spare time Dan also writes scripts for InDesign (Make Book JacketProper Fraction Pro, and more). Dan teaches just about anything web, video, or print related: HTML, CSS, JavaScript, Figma, Adobe XD, After Effects, Premiere Pro, Photoshop, Illustrator, InDesign, and more.

More articles by Dan Rodney

How to Learn JavaScript

Master JavaScript with hands-on training. JavaScript is one of the world's most widely-used coding languages. Learn JavaScript and its libraries to start creating interactive websites and mobile apps.

Yelp Facebook LinkedIn YouTube Twitter Instagram