Skip to content

Latest commit

 

History

History
253 lines (151 loc) · 6.58 KB

File metadata and controls

253 lines (151 loc) · 6.58 KB

📘 05 - Loops in JavaScript

Loops are fundamental in programming, allowing you to execute a block of code multiple times. JavaScript provides several types of loops to handle different scenarios.


🔁 Types of Loops in JavaScript

1. for Loop

The for loop is used when the number of iterations is known. It consists of three parts: initialization, condition, and increment/decrement.

Syntax:

for (initialization; condition; increment) {
  // code block to be executed
}

Example:

for (let i = 0; i < 5; i++) {
  console.log("Iteration:", i);
}

This loop will print numbers from 0 to 4.(Codecademy)

2. while Loop

The while loop executes a block of code as long as the specified condition evaluates to true. It's useful when the number of iterations is not known beforehand.(MDN Web Docs)

Syntax:

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

Example:

let i = 0;
while (i < 5) {
  console.log("Iteration:", i);
  i++;
}

This loop will also print numbers from 0 to 4.

3. do...while Loop

The do...while loop is similar to the while loop, but it guarantees that the code block is executed at least once before the condition is tested.

Syntax:

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

Example:

let i = 0;
do {
  console.log("Iteration:", i);
  i++;
} while (i < 5);

This loop will print numbers from 0 to 4.(Codecademy)

4. for...in Loop

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

Syntax:

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

Example:

const person = { name: "Alice", age: 25 };
for (let key in person) {
  console.log(key + ": " + person[key]);
}

This loop will print:

name: Alice
age: 25

5. for...of Loop

The for...of loop is used to iterate over iterable objects like arrays, strings, maps, etc.

Syntax:

for (let value of iterable) {
  // code block to be executed
}

Example:

const numbers = [1, 2, 3];
for (let num of numbers) {
  console.log(num);
}

This loop will print:

1
2
3

🧠 Choosing the Right Loop

  • for loop: Use when the number of iterations is known.
  • while loop: Use when the number of iterations is not known and depends on a condition.
  • do...while loop: Use when the loop must execute at least once.
  • for...in loop: Use to iterate over object properties.
  • for...of loop: Use to iterate over iterable objects like arrays and strings.(GeeksforGeeks)

⚠️ Common Pitfalls

  • Infinite Loops: Ensure that the loop's terminating condition will eventually be false.
  • Off-by-One Errors: Be careful with loop boundaries to avoid missing iterations or overstepping array bounds.
  • Using for...in with Arrays: Avoid using for...in to iterate over arrays, as it iterates over all enumerable properties, not just array elements. Use for, for...of, or array methods like forEach instead.

💬 Interview Questions & Answers

1. What is the difference between for and while loops?

Answer: Both for and while loops are used for iteration. The for loop is generally used when the number of iterations is known, as it includes initialization, condition, and increment/decrement in one line. The while loop is preferred when the number of iterations is not known and depends on a condition evaluated before each iteration.

2. How does a do...while loop differ from a while loop?

Answer: A do...while loop executes the code block once before checking the condition, ensuring that the block is executed at least once. In contrast, a while loop checks the condition before executing the code block, so the block may not execute at all if the condition is false initially.

3. Can you explain the use of for...in and for...of loops?

Answer: The for...in loop is used to iterate over the enumerable properties (keys) of an object. The for...of loop is used to iterate over iterable objects like arrays, strings, maps, etc., accessing their values directly.

4. What are potential issues when using for...in with arrays?

Answer: Using for...in with arrays can lead to unexpected behavior because it iterates over all enumerable properties, including those inherited through the prototype chain. This can result in iterating over properties that are not actual elements of the array. It's recommended to use for, for...of, or array methods like forEach for arrays.

5. How can you prevent infinite loops?

Answer: To prevent infinite loops, ensure that the loop's terminating condition will eventually evaluate to false. This typically involves correctly updating variables involved in the condition within the loop body.

6. What is an off-by-one error?

Answer: An off-by-one error occurs when a loop iterates one time too many or one time too few. This often happens due to incorrect loop boundaries, such as using < instead of <= in the loop condition.

7. Can you provide an example of using a for loop to iterate over an array?

Answer: Certainly!

const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

This loop will print:

apple
banana
cherry

📚 Additional Resources


🔗 Connect with Me


© 2025 CodeHarborHub. All rights reserved.


Feel free to reach out if you have any questions or need further clarification on any of these topics!