🐚 Loops Workshop

Create a website that populates a page with content using a JavaScript loop. The "content" doesn't necessarily have to be text. Experiment with appending different content types to the DOM.

🌱 Extra: Try adding a random function to your script to create unpredictable outcomes.

Check out this energy doc if you are having trouble getting started →

Code examples

A standard for loop

In this example, we first let i equal 0. Next, we tell the program to continue looping as long as i is less than 100. Lastly, we iterate i using the operator ++. Notice that this will only run the loop 99 times. Can you tell why? How would we loop exactly 100 times? More on for loops here.

// do something 100 times 
for (let i = 0; i < 100; i++) {
  // anything inside this block runs 100 times!
}

A random item from an array

Replace itemsArray with your array's name. randomItem will equal a random item from the array. Can you see how this works? You can also put this inside a function so that you can reuse it over and over.

const randomItem = itemsArray[Math.floor(Math.random() * itemsArray.length)];

A random color function

Similar to the previous code but in this example we are generating a random hexadecimal color code.

// function to return a random color
function generateRandomColor() {
  const randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
  return randomColor;
}

Append an element to the DOM

Make a new element in JavaScript and append it to the DOM (HTML page). You could do this inside your loop to append multiple items to fill up your page.

// Create the element
const el = document.createElement('div');
// Add a class name to it
el.classList = 'coconut';
// Add a style to it if you'd like.
el.style.backgroundColor = generateRandomColor();
// Append the element to the fruits element
document.querySelector(".fruits").appendChild(el)

Resources

If you get stuck along the way. You can use the following websites to find code examples...

Our sites

Help

If you need help please add your name to this list or ask in Campfire