JavaScript Fundamentals / Control Flow

Loops

πŸ”„ Understanding Loops

Loops in JavaScript are used to execute a block of code repeatedly without writing the same code multiple times. They are especially useful when you need to perform the same task over and over, often with different values, making your code shorter, cleaner, and more efficient.


πŸ”° for Loop

The for loop repeats a block of code a specific number of times. It contains initialization, condition, and increment/decrement in one line.

Syntax :

for (initialization; condition; increment/decrement) { 
    // Code to execute 
}

Example :

Loop to print numbers from 1 to 3

for (let i = 1; i <= 3; i++) {
	console.log("Count:", i);
}
Count: 1
Count: 2
Count: 3

πŸ”… Explanation:

  • Initializes the counter variable (let i = 1).

  • Tests the condition (i <= 3); runs while true.

  • Executes the loop body and increments the counter (i++).


➑️ while Loop

The while loop executes as long as the condition is true. It can be thought of as a repeating if statement.

Syntax :

while (condition) {
    // Code to execute
}

Example :

In this example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:

let i = 0;
let text = "";

while (i < 10) {
   text += "The number is " + i + "\\n";
   i++;
}
console.log(text);
The nume is 0
The nume is 1
The nume is 2
The nume is 3
The nume is 4
The nume is 5
The nume is 6
The nume is 7
The nume is 8
The nume is 9

βœ”οΈ Explanation:

  • i starts at 0.

  • The loop runs while i is less than 10.

  • On each loop, it adds "The number is i" to text and increases i.

  • Once i reaches 10, the loop stops.


🏷️ do while Loop

The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax :

do {  
  *// code block to be executed*
}
while (*condition*);

Example :

let i = 0;
let text = "";

do {
   text += "The number is " + i + "\\n";
   i++;
} while (i < 10);

console.log(text);
The nume is 0
The nume is 1
The nume is 2
The nume is 3
The nume is 4
The nume is 5
The nume is 6
The nume is 7
The nume is 8
The nume is 9

In this example:

  • Executes the code block first.

  • Checks the condition (i < 10) after each iteration.

Why use do...while? Even if the condition is false on the first check, the loop runs once before checking.


♦️ For In Loop

The JavaScript for in statement loops through the properties of an Object.

Syntax :

for (key in object) {  
    // *code block to be executed*
}

Example :

const person = { fname: "John", lname: "Doe", age: 25 };
let text = "";

for (let x in person) {
    text += person[x] + " ";
}

console.log(text);
Jhon Doe 25

Explanation:

  • for (let x in person) loops through the keys: "fname", "lname", "age"

  • person[x] gets the value for each key:

    • person["fname"] β†’ "John"

    • person["lname"] β†’ "Doe"

    • person["age"] β†’ 25

So, all values are added to text as a single string.


πŸ–‡οΈ For Of Loop

  • The JavaScript for of statement loops through the values of an iterable object.

  • It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:

Syntax :

for (variable of iterable) {  
    // *code block to be executed*
}
  • variable - For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.

  • iterable - An object that has iterable properties.

Example :

let a = [1, 2, 3, 4, 5];
for (let val of a) {
    console.log(val);
}
1
2
3
4
5

Explanation:

  • for...of is used to loop through values of an iterable like an array.

  • In each iteration, val holds the current element of the array a.


▢️ Break and Continue

  • The break statement "jumps out" of a loop.

❇️ How does Break Work?

Example :

for (let i = 1; i < 6; i++) {
   if (i == 4) {
      break;
   }
   console.log(i);
}
1
2
3

πŸ”΄ Explanation:

  • The loop starts at i = 1 and continues while i < 6

  • When i == 4, the break statement is triggered, and the loop stops immediately

  • So it prints only 1, 2, and 3


  • The continue statement "jumps over" one iteration in the loop.

❇️ How Does Continue Work?

If continue is used in a for loop, the control flow jumps to the test expression after skipping the current iteration.

Example :

Continue to print only odd Numbers smaller than 10

for (let i = 0; i < 10; i++) {
    if (i % 2 == 0) {
       continue;
     }
     console.log(i);
}
1
3
5
7
9

πŸ“ Explanation:

  • The loop runs from i = 0 to i < 10

  • i % 2 == 0 checks if i is even

  • If i is even, continue skips that iteration

  • So only odd numbers (1, 3, 5, 7, 9) are printed


πŸ†š Continue vs Break

The major difference between the continue and break statement is that the break statement breaks out of the loop completely while continue is used to break one statement and iterate to the next statement.