JAVASCRIPT Tutorial

for and foreach

Concept:

'for' and 'foreach' are loop constructs used to iterate over a sequence of values. They allow you to execute a specific block of code repeatedly.

Key Concepts:

  • Initialization: Setting the initial value of a counter variable.
  • Condition: The condition that determines when to exit the loop.
  • Increment/Decrement: The change applied to the counter variable after each iteration.
  • Loop Body: The code that is executed repeatedly within the loop.

Steps to Create a 'for' Loop:

  1. Declare and initialize a counter variable.
  2. Specify the loop condition.
  3. Define the increment/decrement step.
  4. Repeat the loop body while the condition is met.

Steps to Create a 'foreach' Loop:

  1. Declare the loop variable.
  2. Specify the sequence of values to iterate over.
  3. Repeat the loop body for each value in the sequence.

JavaScript Example:

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

// foreach loop
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
  console.log(`Number: ${number}`);
});

Additional Tips:

  • Use 'for' loops when you know the exact number of iterations.
  • Use 'foreach' loops when you want to iterate over a collection or array.
  • Ensure the loop condition eventually becomes false to prevent infinite loops.
  • Use clear and descriptive variable names to enhance readability.