javascript

examples

examples.js
/**
 * =====================================================
 * 4.3 FOR LOOPS - EXAMPLES
 * =====================================================
 * Controlled iteration with counter variables
 */

// =====================================================
// 1. BASIC FOR LOOP
// =====================================================

console.log('--- Basic For Loop ---');

// Count from 0 to 4
for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i}`);
}

// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
  console.log(`Count: ${i}`);
}

// =====================================================
// 2. COUNTING VARIATIONS
// =====================================================

console.log('\n--- Counting Variations ---');

// Count by 2s
console.log('By 2s:');
for (let i = 0; i <= 10; i += 2) {
  console.log(i); // 0, 2, 4, 6, 8, 10
}

// Count down
console.log('Countdown:');
for (let i = 5; i >= 1; i--) {
  console.log(i); // 5, 4, 3, 2, 1
}

// Multiply
console.log('Powers of 2:');
for (let i = 1; i <= 64; i *= 2) {
  console.log(i); // 1, 2, 4, 8, 16, 32, 64
}

// =====================================================
// 3. ARRAY ITERATION
// =====================================================

console.log('\n--- Array Iteration ---');

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

// Basic array iteration
for (let i = 0; i < colors.length; i++) {
  console.log(`${i}: ${colors[i]}`);
}

// Optimized with cached length
console.log('\nWith cached length:');
for (let i = 0, len = colors.length; i < len; i++) {
  console.log(`${i}: ${colors[i]}`);
}

// Reverse iteration
console.log('\nReverse order:');
for (let i = colors.length - 1; i >= 0; i--) {
  console.log(`${i}: ${colors[i]}`);
}

// =====================================================
// 4. MULTIPLE VARIABLES
// =====================================================

console.log('\n--- Multiple Variables ---');

// Two variables moving in opposite directions
for (let left = 0, right = 5; left < right; left++, right--) {
  console.log(`left: ${left}, right: ${right}`);
}

// Fibonacci sequence
console.log('\nFibonacci:');
for (let a = 0, b = 1, temp; a <= 100; temp = a, a = b, b = temp + b) {
  console.log(a);
}

// =====================================================
// 5. NESTED LOOPS
// =====================================================

console.log('\n--- Nested Loops ---');

// Coordinate pairs
console.log('Coordinate pairs:');
for (let x = 0; x < 3; x++) {
  for (let y = 0; y < 3; y++) {
    console.log(`(${x}, ${y})`);
  }
}

// Multiplication table
console.log('\nMultiplication Table (1-5):');
for (let i = 1; i <= 5; i++) {
  let row = '';
  for (let j = 1; j <= 5; j++) {
    row += (i * j).toString().padStart(4);
  }
  console.log(row);
}

// =====================================================
// 6. PATTERN GENERATION
// =====================================================

console.log('\n--- Pattern Generation ---');

// Right triangle
console.log('Right Triangle:');
for (let i = 1; i <= 5; i++) {
  console.log('*'.repeat(i));
}

// Pyramid
console.log('\nPyramid:');
const height = 5;
for (let i = 1; i <= height; i++) {
  const spaces = ' '.repeat(height - i);
  const stars = '*'.repeat(2 * i - 1);
  console.log(spaces + stars);
}

// Number pattern
console.log('\nNumber Pattern:');
for (let i = 1; i <= 5; i++) {
  let row = '';
  for (let j = 1; j <= i; j++) {
    row += j;
  }
  console.log(row);
}

// =====================================================
// 7. BREAK STATEMENT
// =====================================================

console.log('\n--- Break Statement ---');

// Find first match
const numbers = [3, 7, 2, 9, 5, 1, 8];
let found = null;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > 5) {
    found = numbers[i];
    console.log(`Found ${found} at index ${i}`);
    break; // Stop searching
  }
}

// Break with condition
console.log('\nBreak at 5:');
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0, 1, 2, 3, 4
}

// =====================================================
// 8. CONTINUE STATEMENT
// =====================================================

console.log('\n--- Continue Statement ---');

// Skip even numbers
console.log('Odd numbers only:');
for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) continue;
  console.log(i); // 1, 3, 5, 7, 9
}

// Skip specific values
const items = ['apple', null, 'banana', undefined, 'cherry'];
console.log('\nValid items only:');
for (let i = 0; i < items.length; i++) {
  if (items[i] == null) continue;
  console.log(items[i]);
}

// =====================================================
// 9. LABELED LOOPS
// =====================================================

console.log('\n--- Labeled Loops ---');

// Break from nested loop
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    console.log(`i=${i}, j=${j}`);
    if (i === 1 && j === 1) {
      console.log('Breaking outer loop!');
      break outer;
    }
  }
}

// Continue outer loop
console.log('\nContinue outer:');
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) {
      continue outer;
    }
    console.log(`i=${i}, j=${j}`);
  }
}

// =====================================================
// 10. COMMON PATTERNS
// =====================================================

console.log('\n--- Common Patterns ---');

// Sum of array
const nums = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < nums.length; i++) {
  sum += nums[i];
}
console.log('Sum:', sum); // 15

// Maximum value
let max = nums[0];
for (let i = 1; i < nums.length; i++) {
  if (nums[i] > max) {
    max = nums[i];
  }
}
console.log('Max:', max); // 5

// Count occurrences
const text = 'hello world';
let lCount = 0;
for (let i = 0; i < text.length; i++) {
  if (text[i] === 'l') {
    lCount++;
  }
}
console.log("'l' count:", lCount); // 3

// Reverse string
let reversed = '';
for (let i = text.length - 1; i >= 0; i--) {
  reversed += text[i];
}
console.log('Reversed:', reversed);

// =====================================================
// 11. BUILDING ARRAYS
// =====================================================

console.log('\n--- Building Arrays ---');

// Create array of squares
const squares = [];
for (let i = 1; i <= 10; i++) {
  squares.push(i * i);
}
console.log('Squares:', squares);

// Filter values
const values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = [];
for (let i = 0; i < values.length; i++) {
  if (values[i] % 2 === 0) {
    evens.push(values[i]);
  }
}
console.log('Evens:', evens);

// Transform values
const doubled = [];
for (let i = 0; i < values.length; i++) {
  doubled.push(values[i] * 2);
}
console.log('Doubled:', doubled);

// =====================================================
// 12. 2D ARRAYS
// =====================================================

console.log('\n--- 2D Arrays ---');

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

// Print matrix
console.log('Matrix:');
for (let row = 0; row < matrix.length; row++) {
  console.log(matrix[row].join(' '));
}

// Sum all elements
let matrixSum = 0;
for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[row].length; col++) {
    matrixSum += matrix[row][col];
  }
}
console.log('Matrix sum:', matrixSum); // 45

// Find value in matrix
const target = 5;
for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[row].length; col++) {
    if (matrix[row][col] === target) {
      console.log(`Found ${target} at [${row}][${col}]`);
    }
  }
}

// =====================================================
// 13. LOOP VARIATIONS
// =====================================================

console.log('\n--- Loop Variations ---');

// Empty initialization
let counter = 0;
for (; counter < 5; counter++) {
  console.log('Counter:', counter);
}

// Empty update (updated in body)
for (let i = 0; i < 5; ) {
  console.log('i is:', i);
  i += 2; // Update here
}

// Infinite loop with break
let x = 0;
for (;;) {
  console.log('x:', x);
  x++;
  if (x >= 3) break;
}

// =====================================================
// 14. SCOPE DEMONSTRATION
// =====================================================

console.log('\n--- Scope with let vs var ---');

// let has block scope (correct behavior)
for (let i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log('let i:', i);
  }, 10);
}
// Output after timeout: 0, 1, 2

// var has function scope (problematic)
for (var j = 0; j < 3; j++) {
  setTimeout(() => {
    console.log('var j:', j);
  }, 20);
}
// Output after timeout: 3, 3, 3

// =====================================================
// 15. PERFORMANCE CONSIDERATIONS
// =====================================================

console.log('\n--- Performance Tips ---');

// Avoid function calls in condition when possible
const largeArray = Array.from({ length: 1000 }, (_, i) => i);

// Less efficient
console.time('Without cache');
for (let i = 0; i < largeArray.length; i++) {
  // Process
}
console.timeEnd('Without cache');

// More efficient
console.time('With cache');
for (let i = 0, len = largeArray.length; i < len; i++) {
  // Process
}
console.timeEnd('With cache');

// =====================================================
// SUMMARY
// =====================================================

console.log('\n--- Summary ---');
console.log(`
For Loop Structure:
  for (initialization; condition; update) {
      // body
  }

Key Features:
  • initialization - runs once before loop
  • condition - checked before each iteration
  • update - runs after each iteration
  • break - exits loop immediately
  • continue - skips to next iteration
  • labels - control nested loops

Common Uses:
  • Counting (up or down)
  • Array iteration with index access
  • Building new arrays
  • Pattern generation
  • 2D array traversal
`);
Examples - JavaScript Tutorial | DeepML