JavaScript For and For-In Loops | Java Script Tutorial - Learn with VOKS
Back Next

JavaScript For and For-In Loops


Loops in JavaScript allow you to repeat a block of code multiple times. The for loop and for-in loop are two commonly used types, each serving different purposes. They help control the flow of your program and automate repetitive tasks.


1️⃣ The for Loop

A for loop repeats a block of code a specific number of times.

Syntax:

for(initialization; condition; increment/decrement) {
  // code to execute
}
  • Initialization → sets a starting point (e.g., let i = 0)
  • Condition → loop runs while this is true
  • Increment/Decrement → changes the counter each iteration

Example: Counting 1 to 5

for(let i = 1; i <= 5; i++) {
  console.log("Number " + i);
}

// Output: Number 1, Number 2, Number 3, Number 4, Number 5
  • i++ → increases i by 1 after each loop iteration
  • Loop stops when i > 5


2️⃣ The for-in Loop

The for-in loop is used to iterate over the keys (properties) of an object or indices of an array.

Syntax:

for (let key in objectOrArray) {
  // code to execute
}

Example: Iterating Over Object Properties

let person = {name: "Alice", age: 25, city: "Paris"};

for (let key in person) {
  console.log(key + ": " + person[key]);
}

// Output:
// name: Alice
// age: 25
// city: Paris

Example: Iterating Over Array Indices

let fruits = ["Apple", "Banana", "Cherry"];

for (let index in fruits) {
  console.log(index + ": " + fruits[index]);
}

// Output:
// 0: Apple
// 1: Banana
// 2: Cherry
  • for-in is best for objects, but can be used for arrays too
  • for-of (not covered here) is better for array values directly


3️⃣ Loop Control Statements

You can control loops using break and continue:

breakexit the loop immediately

for(let i = 1; i <= 5; i++) {
  if(i === 3) {
    break; // stops loop when i = 3
  }
  console.log(i);
}

// Output: 1, 2

continueskip current iteration

for(let i = 1; i <= 5; i++) {
  if(i === 3) {
    continue; // skips iteration when i = 3
  }
  console.log(i);
}

// Output: 1, 2, 4, 5


Compilation of Entire Code

Explanation:

  • showForLoop() → counts 1–5 using a for loop
  • showForInLoop() → displays object properties using for-in
  • showControlFlow() → demonstrates break and continue in a loop


Example Code:
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript For & For-In Loops</title>
  <style>
    body { font-family: Arial; padding: 20px; }
    button { padding: 10px 20px; margin: 5px; cursor: pointer; }
    p { font-size: 18px; color: darkgreen; }
  </style>
</head>
<body>

  <h1>For & For-In Loops Demo</h1>

  <p id="demo">Click a button to see results</p>

  <button onclick="showForLoop()">Show For Loop</button>
  <button onclick="showForInLoop()">Show For-In Loop</button>
  <button onclick="showControlFlow()">Loop Control Example</button>

  <script>
    // For Loop
    function showForLoop() {
      let result = "For Loop Output:<br>";
      for(let i = 1; i <= 5; i++) {
        result += "Number " + i + "<br>";
      }
      document.getElementById("demo").innerHTML = result;
    }

    // For-In Loop
    function showForInLoop() {
      let person = {name: "Alice", age: 25, city: "Paris"};
      let result = "For-In Loop Output:<br>";
      for(let key in person) {
        result += key + ": " + person[key] + "<br>";
      }
      document.getElementById("demo").innerHTML = result;
    }

    // Loop Control Example
    function showControlFlow() {
      let result = "Loop Control Output:<br>";
      for(let i = 1; i <= 5; i++) {
        if(i === 3) {
          result += "Skipping 3<br>";
          continue; // skip 3
        }
        if(i === 5) {
          result += "Breaking at 5<br>";
          break; // stop loop
        }
        result += "Number " + i + "<br>";
      }
      document.getElementById("demo").innerHTML = result;
    }
  </script>

</body>
</html>
Java Script
Introduction Application of JavaScript Defining JavaScript Client-Side JavaScript JavaScript Syntax JavaScript Varaibles JavaScript Operators JavaScript Statements JavaScript Arrays Sorting JavaScript Array JavaScript Functions JavaScript Objects JavaScript For and For-In Loops JavaScript Cookies JavaScript Form Validation JavaScript Error and Exception Handling JavaScript Animation JavaScript Switch Case and While Loops
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL