Back to Web Development
2026-01-065 min read

For Loops (Web Development)

Learn For Loops (Web Development) step by step with clear examples and exercises.

Title: For Loops (Web Development) — A full guide for Practical Depth

Why This Matters

For loops are a fundamental building block of web development, enabling us to repeat blocks of code a specific number of times or until a certain condition is met. Understanding and mastering for loops will empower you to create more efficient and dynamic websites, tackle complex programming tasks, and debug common errors. In interviews, demonstrating proficiency in using for loops can significantly boost your chances of landing that dream web development job.

Prerequisites

Core Concept

A for loop is a control structure that allows us to iterate over a specified range of values or an array, executing the same block of code repeatedly with each iteration. The syntax for a basic for loop in JavaScript is as follows:

for (initialization; condition; increment/decrement) {
// Code to be executed in each iteration
}
  • Initialization: This statement initializes the counter variable, usually named i or counter, with a starting value.
  • Condition: This statement checks whether the loop should continue executing based on a Boolean expression. If the condition is true, the loop continues; otherwise, it terminates.
  • Increment/Decrement: This statement updates the counter variable after each iteration, typically incrementing by 1 but can be customized as needed.

For Loop Example (Expanded)

Let's create a simple for loop that prints numbers from 1 to 10 using JavaScript in an HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>For Loop Example</title>
</head>
<body>
<h1>Numbers from 1 to 10 using a For Loop:</h1>
<ul id="numbers"></ul>

<script>
const numbers = document.getElementById('numbers');
for (let i = 1; i <= 10; i++) {
const listItem = document.createElement('li');
listItem.textContent = i;
numbers.appendChild(listItem);
}
</script>
</body>
</html>

In this example, we create an unordered list and use a for loop to iterate from 1 to 10, creating and appending a new `` element for each number.

Worked Example

Now let's take it up a notch by implementing a more practical example: Creating a dynamic password generator that generates strong passwords using a for loop.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Password Generator</title>
</head>
<body>
<h1>Generate a Strong Password:</h1>
<button id="generatePassword">Generate Password</button>
<p id="password"></p>

<script>
const generatePassword = () => {
const lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz';
const upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789';
const specialChars = '@#$%^&*()_+-=[]{}|;:,.<>?';
let password = '';

for (let i = 0; i < 8; i++) {
const randomIndex = Math.floor(Math.random() * 4);
switch (randomIndex) {
case 0:
password += lowerCaseLetters[Math.floor(Math.random() * lowerCaseLetters.length)];
break;
case 1:
password += upperCaseLetters[Math.floor(Math.random() * upperCaseLetters.length)];
break;
case 2:
password += numbers[Math.floor(Math.random() * numbers.length)];
break;
case 3:
password += specialChars[Math.floor(Math.random() * specialChars.length)];
break;
}
}

document.getElementById('password').textContent = password;
};

const generatePasswordButton = document.getElementById('generatePassword');
generatePasswordButton.addEventListener('click', generatePassword);
</script>
</body>
</html>

In this example, we create a button that generates a strong password by using a for loop to select random characters from four different character sets (lowercase letters, uppercase letters, numbers, and special characters). Each time the button is clicked, a new password is generated.

Common Mistakes

1. Forgetting to initialize the counter variable

Ensure that you initialize the counter variable in the for loop to avoid errors such as "i is not defined."

2. Incorrect condition

Check that your condition evaluates to a Boolean value and updates appropriately with each iteration.

3. Improper increment/decrement

Make sure that you update the counter variable correctly, either by incrementing or decrementing it as needed.

Common Mistakes (Expanded)

1. Forgetting to initialize the counter variable

Ensure that you initialize the counter variable in the for loop to avoid errors such as "i is not defined."

Example:

for (let i; i < 10; i++) { // Error: i is not initialized
console.log(i);
}

Correct:

for (let i = 0; i < 10; i++) {
console.log(i);
}

2. Incorrect condition

Check that your condition evaluates to a Boolean value and updates appropriately with each iteration.

Example:

for (let i = 0; i > 10; i++) { // Error: condition is not met when i < 10
console.log(i);
}

Correct:

for (let i = 0; i <= 10; i++) {
console.log(i);
}

3. Improper increment/decrement

Make sure that you update the counter variable correctly, either by incrementing or decrementing it as needed.

Example:

for (let i = 0; i < 10; i++) { // Error: i is not being incremented
console.log(i);
}

Correct:

for (let i = 0; i < 10; i++) {
console.log(i);
i++;
}

Practice Questions

  1. Write a for loop that prints even numbers from 2 to 20.
  2. Implement a for loop that sums all the numbers in an array.
  3. Create a for loop that checks if a given number is prime or not.
  4. Write a for loop that generates Fibonacci sequence up to the 15th term.
  5. Implement a for loop that reverses an array of strings.
  6. (Bonus) Write a for loop that finds all palindromic numbers between 1 and 100.
  7. (Bonus) Implement a for loop that calculates the factorial of a given number.
  8. (Bonus) Create a for loop that generates all possible combinations of a given set of characters (e.g., generating all 4-letter passwords using the characters 'a', 'b', 'c', and 'd').

FAQ

Q: Can I use a for loop with arrays in JavaScript?

A: Yes, you can iterate over an array using a for loop by using the array.length property as the condition and incrementing the counter variable by 1 after each iteration.

Example:

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

Q: Is it possible to create an infinite for loop in JavaScript?

A: An infinite for loop occurs when the condition is never met, causing the loop to continue indefinitely. To avoid this, make sure that your condition will eventually be false or set a maximum number of iterations.

Example:

for (let i = 0; true; i++) { // Infinite loop
console.log(i);
}

Correct:

for (let i = 0; i < 10; i++) {
console.log(i);
}

Q: Can I use a for loop with strings in JavaScript?

A: Yes, you can iterate over a string using a for loop by treating it as an array of characters and accessing each character using the index (string[index]). However, this is less efficient than using methods like String.prototype.split() or String.prototype.charAt().

Example:

const myString = 'Hello World';
for (let i = 0; i < myString.length; i++) {
console.log(myString[i]);
}
For Loops (Web Development) | Web Development | XQA Learn