7. for loop in JavaScript

Shofique RianShofique Rian
4 min read

Certainly! The for loop in JavaScript is a control flow statement that allows you to repeatedly execute a block of code a certain number of times. Here's a detailed breakdown of the for loop:

Syntax:

for (initialization; condition; update) {
  // Code to be executed in each iteration
}
  • Initialization: This part is executed once before the loop starts. It usually initializes a counter variable.

  • Condition: The loop continues to execute as long as the condition is true.

  • Update: This part is executed after each iteration. It's typically used to update the counter variable.

  • Code Block: The block of code inside the curly braces {} is the code to be executed in each iteration.

Example:

for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i}`);
}

Breakdown:

  1. Initialization (let i = 0;): Set up a variable i and initialize it to 0.

  2. Condition (i < 5;): The loop will continue as long as i is less than 5.

  3. Code Block (console.log(Iteration ${i});): This code will execute in each iteration, logging the current value of i.

  4. Update (i++): After each iteration, increment the value of i by 1.

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

Additional Notes:

  • The initialization, condition, and update sections are optional, but you must have semicolons to separate them.

  • You can use any valid JavaScript expression in the initialization, condition, and update sections.

  • The loop will continue to execute as long as the condition is true. Once the condition becomes false, the loop will exit.

  • The for...of loop is also available for iterating over the values of an iterable (e.g., arrays, strings).

  • The for...in loop is used to iterate over the properties of an object.

Remember, the for loop is a fundamental construct in programming, and mastering it will give you a powerful tool for controlling the flow of your code.

example

Certainly! Let's dive into a more detailed example of a for loop in JavaScript. In this example, we'll create a loop to calculate the factorial of a number. The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n.

// Function to calculate the factorial of a number
function calculateFactorial(number) {
  // Check if the number is non-negative
  if (number < 0) {
    return "Invalid input. Factorial is not defined for negative numbers.";
  }

  // Initialize the result to 1
  let factorialResult = 1;

  // Loop to calculate the factorial
  for (let i = 1; i <= number; i++) {
    factorialResult *= i;
  }

  // Return the factorial result
  return factorialResult;
}

// Example: Calculate the factorial of 5
const result = calculateFactorial(5);
console.log(`The factorial of 5 is: ${result}`);

Breakdown:

  1. Function Definition (calculateFactorial):

    • Declares a function named calculateFactorial that takes a parameter number.
  2. Input Validation:

    • Checks if the input number is non-negative. If it's negative, it returns an error message.
  3. Factorial Calculation Loop (for loop):

    • Initializes i to 1.

    • The loop continues as long as i is less than or equal to the input number.

    • In each iteration, multiplies factorialResult by the current value of i.

    • Increments i by 1 in each iteration.

  4. Return Result:

    • Returns the calculated factorial result.
  5. Example Usage:

    • Calls the calculateFactorial function with an input of 5.

    • Prints the result to the console.

Output:

The factorial of 5 is: 120

In this example, the for loop is used to calculate the factorial of a number. Understanding how the loop initializes, checks a condition, executes a code block, and updates is crucial for writing effective and efficient loops in JavaScript.

Examples:

Print numbers 1 to 5:

JavaScript

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

Loop through an array:

JavaScript

const fruits = ["apple", "banana", "orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Tips for beginners:

  • Start with simple examples like the ones above to get comfortable with the syntax.

  • Use descriptive variable names to make your code easier to understand.

  • Be careful when modifying variables inside the loop to avoid unexpected behavior.

  • Think about how many times you want the loop to run and what logic you need to control it.

  • Practice makes perfect! Try using for loops in different situations to solidify your understanding.

Certainly! Iteration in JavaScript refers to the process of repeatedly executing a block of code. There are several ways to achieve iteration in JavaScript. Here, I'll cover some basic concepts and provide examples for beginners.

Iterates over the properties of an object.

const person = {
  name: 'John',
  age: 30,
  occupation: 'Developer',
};

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

Output:

name: John
age: 30
occupation: Developer

for (let key in obj){

console.log(${key}: ${obj[key]})

}

0
Subscribe to my newsletter

Read articles from Shofique Rian directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shofique Rian
Shofique Rian