javascript

examples

examples.js
/**
 * =====================================================
 * 4.5 FOR...OF AND FOR...IN LOOPS - EXAMPLES
 * =====================================================
 * Specialized iteration constructs
 */

// =====================================================
// 1. BASIC FOR...OF WITH ARRAYS
// =====================================================

console.log('--- for...of with Arrays ---');

const fruits = ['apple', 'banana', 'cherry'];

for (const fruit of fruits) {
  console.log(fruit);
}

// With modification (use let)
console.log('\nWith transformation:');
for (const fruit of fruits) {
  console.log(fruit.toUpperCase());
}

// =====================================================
// 2. FOR...OF WITH INDEX (using entries)
// =====================================================

console.log('\n--- for...of with Index ---');

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

for (const [index, color] of colors.entries()) {
  console.log(`${index}: ${color}`);
}

// =====================================================
// 3. BASIC FOR...IN WITH OBJECTS
// =====================================================

console.log('\n--- for...in with Objects ---');

const person = {
  name: 'John',
  age: 30,
  city: 'New York',
};

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

// =====================================================
// 4. COMPARING FOR...OF AND FOR...IN ON ARRAYS
// =====================================================

console.log('\n--- for...of vs for...in on Arrays ---');

const numbers = [10, 20, 30];

console.log('for...of (values):');
for (const num of numbers) {
  console.log(num, typeof num); // 10, 20, 30 (numbers)
}

console.log('\nfor...in (indices as strings):');
for (const index in numbers) {
  console.log(index, typeof index); // "0", "1", "2" (strings!)
}

// =====================================================
// 5. FOR...IN INCLUDES CUSTOM PROPERTIES
// =====================================================

console.log('\n--- for...in with Custom Properties ---');

const arr = ['a', 'b', 'c'];
arr.customProp = 'extra';

console.log('for...in (includes custom property):');
for (const key in arr) {
  console.log(key); // "0", "1", "2", "customProp"
}

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

// =====================================================
// 6. ITERATING STRINGS
// =====================================================

console.log('\n--- Iterating Strings ---');

const word = 'Hello';

// for...of gives characters
console.log('Characters:');
for (const char of word) {
  console.log(char);
}

// Unicode handling
console.log('\nUnicode (emojis):');
const emoji = '👋🌍🎉';
for (const e of emoji) {
  console.log(e);
}

// =====================================================
// 7. ITERATING MAPS
// =====================================================

console.log('\n--- Iterating Maps ---');

const userRoles = new Map([
  ['admin', { level: 10, permissions: ['all'] }],
  ['editor', { level: 5, permissions: ['edit', 'view'] }],
  ['viewer', { level: 1, permissions: ['view'] }],
]);

// Default iteration (entries)
console.log('Map entries:');
for (const [role, details] of userRoles) {
  console.log(`${role}: Level ${details.level}`);
}

// Keys only
console.log('\nMap keys:');
for (const role of userRoles.keys()) {
  console.log(role);
}

// Values only
console.log('\nMap values:');
for (const details of userRoles.values()) {
  console.log(details.permissions);
}

// =====================================================
// 8. ITERATING SETS
// =====================================================

console.log('\n--- Iterating Sets ---');

const uniqueIds = new Set([1, 2, 3, 2, 1, 4, 5]);

for (const id of uniqueIds) {
  console.log(id); // 1, 2, 3, 4, 5 (duplicates removed)
}

// =====================================================
// 9. OBJECT ITERATION METHODS
// =====================================================

console.log('\n--- Object Iteration Methods ---');

const config = {
  host: 'localhost',
  port: 3000,
  ssl: true,
};

// Object.keys()
console.log('Keys:');
for (const key of Object.keys(config)) {
  console.log(key);
}

// Object.values()
console.log('\nValues:');
for (const value of Object.values(config)) {
  console.log(value);
}

// Object.entries()
console.log('\nEntries:');
for (const [key, value] of Object.entries(config)) {
  console.log(`${key} = ${value}`);
}

// =====================================================
// 10. FILTERING WITH HASOWNPROPERTY
// =====================================================

console.log('\n--- hasOwnProperty Filter ---');

const parent = { inherited: "I'm inherited" };
const child = Object.create(parent);
child.own = "I'm own property";

console.log('Without filter (includes inherited):');
for (const key in child) {
  console.log(key);
}

console.log('\nWith hasOwnProperty filter:');
for (const key in child) {
  if (Object.prototype.hasOwnProperty.call(child, key)) {
    console.log(key);
  }
}

// =====================================================
// 11. BREAK AND CONTINUE
// =====================================================

console.log('\n--- Break and Continue ---');

const items = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// break
console.log("Breaking at 'cherry':");
for (const item of items) {
  if (item === 'cherry') {
    console.log('Found cherry, stopping!');
    break;
  }
  console.log(item);
}

// continue
console.log("\nSkipping items with 'a':");
for (const item of items) {
  if (item.includes('a')) {
    continue;
  }
  console.log(item);
}

// =====================================================
// 12. NESTED ITERATION
// =====================================================

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

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

console.log('Matrix elements:');
for (const row of matrix) {
  for (const cell of row) {
    process.stdout.write(`${cell} `);
  }
  console.log(); // New line
}

// =====================================================
// 13. ITERATING NODELIST (DOM-like simulation)
// =====================================================

console.log('\n--- Simulated NodeList Iteration ---');

// Simulating a NodeList-like structure
const nodes = {
  0: { tagName: 'DIV', id: 'header' },
  1: { tagName: 'P', id: 'intro' },
  2: { tagName: 'SPAN', id: 'footer' },
  length: 3,
  [Symbol.iterator]: function* () {
    for (let i = 0; i < this.length; i++) {
      yield this[i];
    }
  },
};

for (const node of nodes) {
  console.log(`${node.tagName}#${node.id}`);
}

// =====================================================
// 14. ITERATING ARGUMENTS OBJECT
// =====================================================

console.log('\n--- Iterating Arguments ---');

function showArgs() {
  console.log('Arguments:');
  for (const arg of arguments) {
    console.log(`- ${arg}`);
  }
}

showArgs('hello', 42, true, { name: 'test' });

// =====================================================
// 15. PRACTICAL EXAMPLES
// =====================================================

console.log('\n--- Practical Examples ---');

// Sum all values
const prices = [9.99, 14.99, 24.99, 5.99];
let total = 0;
for (const price of prices) {
  total += price;
}
console.log(`Total: $${total.toFixed(2)}`);

// Count occurrences
const text = 'hello world';
const charCount = {};
for (const char of text) {
  charCount[char] = (charCount[char] || 0) + 1;
}
console.log('\nCharacter counts:', charCount);

// Find common properties
const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { b: 4, c: 5, d: 6 };
const common = [];

for (const key in obj1) {
  if (key in obj2) {
    common.push(key);
  }
}
console.log('Common keys:', common);

// =====================================================
// 16. CONVERTING BETWEEN TYPES
// =====================================================

console.log('\n--- Type Conversions ---');

// Object to array of pairs
const settings = { theme: 'dark', fontSize: 14, language: 'en' };
const settingsArray = [];

for (const [key, value] of Object.entries(settings)) {
  settingsArray.push({ key, value });
}
console.log('Settings as array:', settingsArray);

// Array of pairs to object
const pairs = [
  ['x', 1],
  ['y', 2],
  ['z', 3],
];
const coordObject = {};

for (const [key, value] of pairs) {
  coordObject[key] = value;
}
console.log('Coords as object:', coordObject);

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

console.log('\n--- Summary ---');
console.log(`
for...of:
  • Iterates over VALUES of iterables
  • Works with: Arrays, Strings, Maps, Sets, etc.
  • Does NOT work directly with plain objects
  • Use arr.entries() to get index + value

for...in:
  • Iterates over KEYS (property names)
  • Works with: Objects (and arrays, but not recommended)
  • Includes inherited properties
  • Use hasOwnProperty() to filter

Best Practices:
  • Use for...of for arrays and iterables
  • Use for...in for objects (or Object.keys/values/entries)
  • Use const for loop variables when not reassigning
  • Filter inherited properties with hasOwnProperty
`);
Examples - JavaScript Tutorial | DeepML