Skip to content
beginnerPhase 32 · JavaScript Fundamentals

Loops

Master for, while, do-while, for...of, for...in, and break/continue.

30m
0 problems
Topic Progress0%

for Loop

for Loop

Basic Syntax

for (let i = 0; i < 5; i++) {
  console.log(i); // 0, 1, 2, 3, 4
}

Components

// Initialization: let i = 0
// Condition: i < 5
// Increment: i++

for (let i = 0; i < 5; i++) {
  // Code runs 5 times
}

Counting Patterns

// Count up
for (let i = 1; i <= 10; i++) {
  console.log(i); // 1 to 10
}

// Count down
for (let i = 10; i >= 1; i--) {
  console.log(i); // 10 to 1
}

// Step by 2
for (let i = 0; i < 10; i += 2) {
  console.log(i); // 0, 2, 4, 6, 8
}

Looping Through Arrays

const colors = ['red', 'green', 'blue'];

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

break and continue

// break: exit loop
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0, 1, 2, 3, 4
}

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

Nested Loops

for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    console.log(`${i}, ${j}`);
  }
}

Labeled Statements

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) break outer;
    console.log(`${i}, ${j}`);
  }
}

while Loop

while Loop

Basic Syntax

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

do...while

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
// Always runs at least once

When to Use While

// When you don't know how many iterations
let result = 1;
while (result < 1000) {
  result *= 2;
}

// Reading input until condition
let input;
while (input !== 'quit') {
  input = prompt('Enter command:');
}

Avoiding Infinite Loops

// Danger: infinite loop
while (true) {
  console.log('forever');
}

// Safe: with break
while (true) {
  const input = getData();
  if (!input) break;
  process(input);
}

while vs for

// for: when you know iteration count
for (let i = 0; i < 10; i++) { }

// while: when condition-based
while (isRunning) { }

// do...while: when need to run at least once
do {
  // run at least once
} while (condition);

Practical Examples

// Find first even number
const numbers = [1, 3, 4, 7, 8];
let i = 0;
while (i < numbers.length && numbers[i] % 2 !== 0) {
  i++;
}
const firstEven = numbers[i]; // 4

// Retry logic
let attempts = 0;
while (attempts < 3) {
  try {
    fetchData();
    break;
  } catch (e) {
    attempts++;
  }
}

for...of and for...in

for...of and for...in

for...of (Values)

// Arrays
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
  console.log(color);
}

// Strings
const name = 'John';
for (const char of name) {
  console.log(char);
}

// Maps
const map = new Map([['a', 1], ['b', 2]]);
for (const [key, value] of map) {
  console.log(key, value);
}

// Sets
const set = new Set([1, 2, 3]);
for (const value of set) {
  console.log(value);
}

for...in (Keys/Indices)

// Objects
const person = { name: 'John', age: 30 };
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

// Arrays (not recommended)
const arr = ['a', 'b', 'c'];
for (const index in arr) {
  console.log(index); // '0', '1', '2' (strings!)
}

Comparison

const arr = ['a', 'b', 'c'];

// for...of: values
for (const value of arr) {
  console.log(value); // 'a', 'b', 'c'
}

// for...in: indices (as strings)
for (const index in arr) {
  console.log(index); // '0', '1', '2'
}

// Traditional for: index (as number)
for (let i = 0; i < arr.length; i++) {
  console.log(i); // 0, 1, 2
}

Best Practices

// Use for...of for values
for (const item of items) {
  process(item);
}

// Use Object.keys/values/entries for objects
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value);
}

// Avoid for...in for arrays (iterates prototype)
// Use for...of or traditional for instead

Iterables

// Arrays, Strings, Maps, Sets are iterable
const iterable = [1, 2, 3];
for (const value of iterable) { }

// Plain objects are NOT iterable
const obj = { a: 1, b: 2 };
// for (const value of obj) { } // Error!

// Use Object.entries instead
for (const [key, value] of Object.entries(obj)) { }

Practice Problems

0/3solved
Build Loops Component

Create a reusable React component implementing Loops. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Loops Testing

Write unit and integration tests for Loops using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Loops Performance

Optimize Loops for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. What is the difference between for...of and for...in?

Question 1 options

2. When should you use do...while over while?

Question 2 options

3. What does break do in a loop?

Question 3 options

4. Why should you avoid for...in with arrays?

Question 4 options

5. What are plain objects in JavaScript?

Question 5 options

Flashcards

Question

What is the difference between break and continue?

Answer

break exits the loop completely. continue skips the current iteration and moves to the next.

Question

When should you use a while loop?

Answer

When you don't know how many iterations you need and want to loop until a condition is false.

Question

What does for...of iterate over?

Answer

Values of iterable objects like arrays, strings, maps, and sets.

Question

What is the difference between while and do...while?

Answer

while checks condition first. do...while runs at least once before checking.

Question

How do you iterate over object properties?

Answer

Use Object.keys(), Object.values(), or Object.entries() with for...of.

Revision Notes

Key Takeaways

  • 1.for loop is for known iteration count
  • 2.while is for condition-based loops
  • 3.do...while runs at least once
  • 4.for...of iterates values, for...in iterates keys
  • 5.Objects are not iterable directly

Interview Tips

  • Know the difference between for, while, and do...while
  • Understand for...of vs for...in
  • Explain break vs continue
  • Know when to use each loop type

Cheat Sheet

Loops Cheat Sheet

for loop

for (let i = 0; i < 5; i++) { }

while loop

while (condition) { }

do...while

do { } while (condition);

for...of (values)

for (const item of items) { }

for...in (keys)

for (const key in obj) { }

break and continue

break;    // Exit loop
continue; // Skip iteration

Iterables

  • Arrays, Strings, Maps, Sets
  • Objects are NOT iterable
  • Use Object.entries() for objects