JavaScript for Loops Tutorial

What is JavaScript for Loop

  1. A JavaScript for loop is a way to make a certain piece of code run repeatedly for a specific number of times.
  2. We typically use this loop when we already know how many times the code needs to run.
  3. It is one of the most commonly used loops in JavaScript.

Syntax:

for (initialExpression; condition; incrementExpression) {
    // code block to be executed
}
  

initialExpression: This expression is executed once, before the loop starts. It is typically used to initialize a counter variable.

condition: This expression is evaluated before each iteration of the loop. If the condition is true, the code block is executed. Otherwise, the loop terminates.

incrementExpression: This expression is executed after each iteration of the loop. It is typically used to increment the counter variable.

Example

for (let count = 1; count <= 5; count++) {
    console.log("Count: " + count);
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
    

Here, we want to run the code exactly 5 times, from Count: 1 to Count: 5. So, instead of using a while loop, the "for" loop is simpler to manage in such clear-cut scenarios.

Nested for Loops

  1. You can use nested for loops to work with two-dimensional arrays or perform operations on grids and matrices.
  2. Here's an example that prints a simple grid pattern.
for (let row = 1; row <= 3; row++) {
let pattern = "";
for (let col = 1; col <= 3; col++) {
    pattern += "* ";
}
console.log(pattern);
}

The above code will give output like this

* * *
* * *
* * *

Break and continue statements

  1. The break and continue statements can be used to control the flow of a for loop.
  2. The break statement terminates the loop immediately.
  3. The continue statement skips the rest of the current iteration of the loop and moves on to the next iteration.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
    break;
}

if (i % 2 === 0) {
    continue;
}

console.log(i);
}
/*Output:
1
2
*/
  

for...in Loop

  1. The JavaScript for...of loop is mostly used to go through the properties of objects.
  2. It goes over the properties we can count in an object, even the ones it got from its family line.

Syntax:

for (variable in object) {
    // Code to be executed
}

variable: This variable represents the property name for each iteration.

object: The object whose properties you want to iterate.

const person = {
    name: "John",
    age: 30,
    occupation: "Engineer"
};

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

Output of the above code will be

name: John
age: 30
occupation: Engineer

for...of Loop

  1. The for...of statement runs a loop that works on a series of values taken from an iterable object.
  2. Iterable objects cover built-in things like Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), also the arguments object, generators made by generator functions, and iterable things we make ourselves.

Syntax:

for (variable of iterable) {
    // Code to be executed
}

variable: This variable represents the value for each iteration.

iterable: The data structure (array, string, map, set, etc.) you want to iterate over.

Example

const fruits = ["apple", "banana", "cherry", "date"];

for (let fruit of fruits) {
    console.log("Fruit: " + fruit);
}
    
Fruit: apple
Fruit: banana
Fruit: cherry
Fruit: date

When to user for loops over while loops

  1. Definite Number of Iterations. That means when we know how many times the loop will execute.
  2. Iterating Over Arrays or Collections:
  3. Complex Loop Control
  4. Initialization and Update Logic