Loop Magic in Node.js ✨

Turn loops into your coding sidekick! From array jazz to async beats, Node.js loops got the groove. Let's make your code dance! πŸ’ƒπŸ•Ί

Loop Magic in Node.js ✨
Photo by Tine Ivanič / Unsplash

Basic For Loop in Node.js

// Define the range of numbers to loop through
const start = 1;
const end = 5;

// Use a for loop to iterate through the range
for (let i = start; i <= end; i++) {
    // Print the current iteration value
    console.log(`Iteration ${i}`);
}

Learn how to use a simple for loop in Node.js to iterate through a range of numbers.


For Loop with Array in Node.js

// Sample array of names
const names = ['Alice', 'Bob', 'Charlie', 'David'];

// Use a for loop to iterate through the array
for (let i = 0; i < names.length; i++) {
    // Print the current element in the array
    console.log(`Name: ${names[i]}`);
}

Iterate through an array using a for loop in Node.js.


While Loop for Dynamic Iteration in Node.js

// Set an initial condition
let count = 0;

// Define the while loop with a condition
while (count < 3) {
    // Print the current count
    console.log(`Count: ${count}`);

    // Increment the count for the next iteration
    count++;
} 

Utilize a while loop in Node.js for dynamic iteration based on a condition.


Breaking Out of a Loop in Node.js

// Sample array of numbers
const numbers = [10, 20, 30, 40, 50];

// Use a for loop to find and print the first occurrence of a specific number
const targetNumber = 30;
for (let i = 0; i < numbers.length; i++) {
    // Check if the current element is the target number
    if (numbers[i] === targetNumber) {
        // Print the index and value, then exit the loop
        console.log(`Target number found at index ${i}`);
        break;
    }
}

Learn how to use the 'break' statement to exit a loop prematurely in Node.js.


For...of Loop with Arrays in Node.js

// Sample array of colors
const colors = ['Red', 'Green', 'Blue'];

// Use a for...of loop to iterate through the array
for (const color of colors) {
    // Print the current element in the array
    console.log(`Color: ${color}`);
}

Explore the concise for...of loop to iterate through elements in an array in Node.js.


Asynchronous For Loop with Promises in Node.js


// Sample asynchronous function that returns a Promise
function asyncOperation(item) {
    return new Promise(resolve => {
        // Simulate an asynchronous task
        setTimeout(() => {
            resolve(`Processed: ${item}`);
        }, 1000);
    });
}

// Sample array of items
const items = ['A', 'B', 'C'];

// Use an asynchronous for loop with Promises
async function processItemsAsync() {
    for (const item of items) {
        // Await the completion of the asynchronous operation
        const result = await asyncOperation(item);
        // Print the result
        console.log(result);
    }
}

// Call the asynchronous function
processItemsAsync();

Master asynchronous operations with a for loop using Promises in Node.js.


While Loop with Dynamic Condition in Node.js

const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

// Initialize a flag for loop continuation
let continueLoop = true;

// Use a while loop with a dynamic condition
while (continueLoop) {
    // Ask the user whether to continue the loop
    readline.question('Do you want to continue the loop? (yes/no): ', answer => {
        // Update the loop condition based on user input
        continueLoop = answer.toLowerCase() === 'yes';
        readline.close();
    });
    
    // Perform other tasks within the loop if needed
}
πŸ’‘
You need to install the readline

$ npm i -s readline

Create a while loop with a dynamic condition based on user input in Node.js.


Asynchronous Loop with Parallel Execution

const asyncTask1 = async () => {/* async logic */};
const asyncTask2 = async () => {/* async logic */};
const asyncTask3 = async () => {/* async logic */};

// Create an array of asynchronous tasks
const tasks = [asyncTask1(), asyncTask2(), asyncTask3()];

// Use Promise.all to wait for all tasks to complete
const results = await Promise.all(tasks);

// Log the results
console.log('Results:', results);

Execute asynchronous tasks in parallel using Promise.all for optimal performance.


Dynamic While Loop with Event-driven Exit


const EventEmitter = require('events');
const someEventEmitter = new EventEmitter();

// Initialize a flag for loop continuation
let continueLoop = true;

// Listen for the 'stopLoop' event to exit the loop
someEventEmitter.on('stopLoop', () => (continueLoop = false));

// Use a while loop with a dynamic condition
while (continueLoop) {
    // Loop logic
}

Create a dynamic while loop with an event-driven exit condition using EventEmitter.


Iterating Over Object Properties

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

// Use Object.entries to iterate over key-value pairs
for (const [key, value] of Object.entries(user)) {
    console.log(`${key}: ${value}`);
}

Iterate over object properties using Object.entries for concise and readable code.


Looping with Generators

// Define a generator function for a custom range
function* customRange(start, end, step) {
    for (let i = start; i <= end; i += step) {
        yield i;
    }
}

// Use the custom generator in a for...of loop
for (const num of customRange(1, 10, 2)) {
    console.log(num);
}

Use a generator function for custom iteration logic, providing more control over the loop.


Looping with Array.reduce

const numbers = [1, 2, 3, 4, 5];

// Use Array.reduce to calculate the sum of array elements
const sum = numbers.reduce((acc, curr) => acc + curr, 0);

// Log the sum
console.log('Sum:', sum);

Utilize Array.reduce for advanced array transformations, achieving concise and expressive code.


Looping with Map and Async Functions

const items = [1, 2, 3];

// Use Array.map with an asynchronous function
const results = await Promise.all(
    items.map(async (item) => {
        // Perform async operation for each item
        return await someAsyncFunction(item);
    })
);

// Log the results
console.log('Transformed Items:', results);

Combine the power of Array.map and async/await for concise and asynchronous transformations.


Iterating Over Multiple Arrays in Parallel

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];

// Use forEach on one array while accessing the corresponding element in the other
array1.forEach((num, index) => {
    const correspondingElement = array2[index];
    console.log(`Number: ${num}, Corresponding Element: ${correspondingElement}`);
});

Simultaneously iterate over multiple arrays using the forEach method for streamlined parallel processing.


Looping with Set and Unique Values

const duplicateArray = [1, 2, 2, 3, 4, 4, 5];

// Use a Set to store unique values and iterate over them
const uniqueSet = new Set(duplicateArray);
for (const uniqueValue of uniqueSet) {
    console.log('Unique Value:', uniqueValue);
}

Leverage the Set data structure to iterate over unique values in an array.


Looping with Recursive Functions

// Define a recursive function for custom iteration
function recursiveLoop(counter) {
    if (counter <= 0) {
        return; // Base case to exit recursion
    }

    // Log the current counter value
    console.log(`Counter: ${counter}`);

    // Recursive call with decremented counter
    recursiveLoop(counter - 1);
}

// Start the recursive loop with an initial counter value
recursiveLoop(3);

Achieve complex looping logic using recursive functions for elegant and flexible control flow.


Looping with Custom Iterable Objects

// Define a custom iterable object
const customIterable = {
    values: ['apple', 'banana', 'cherry'],
    [Symbol.iterator]: function* () {
        for (const value of this.values) {
            yield value;
        }
    },
};

// Use a for...of loop with the custom iterable object
for (const fruit of customIterable) {
    console.log('Fruit:', fruit);
}

Implement custom iterable objects using Symbol.iterator for specialized and reusable iteration.


Looping with Custom Iteration Logic

// Define a custom iterable object with unique iteration logic
const customIterable = {
    values: [10, 20, 30],
    [Symbol.iterator]: function* () {
        yield* this.values.map(value => value * 2);
    },
};

// Use a for...of loop with the custom iterable
for (const doubledValue of customIterable) {
    console.log('Doubled Value:', doubledValue);
}

Implement a custom iterator with Symbol.iterator to control iteration flow.


Looping with Zip and Unzip Operations

// Zip operation to combine two arrays
const zip = (arr1, arr2) => arr1.map((item, index) => [item, arr2[index]]);
const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];

const zippedArray = zip(array1, array2);
console.log('Zipped Array:', zippedArray);

// Unzip operation to separate a zipped array
const unzip = zippedArr => zippedArr.reduce((acc, val) => (acc[0].push(val[0]), acc[1].push(val[1]), acc), [[], []]);
const [unzippedArray1, unzippedArray2] = unzip(zippedArray);
console.log('Unzipped Arrays:', unzippedArray1, unzippedArray2);

Combine and separate arrays with zip and unzip operations for efficient parallel processing.


Looping with Web Scraping

const axios = require('axios');
const cheerio = require('cheerio');

// Sample URL for web scraping
const url = 'https://example.com/page';

// Loop through multiple pages
for (let page = 1; page <= 3; page++) {
    // Make a request to the page
    const response = await axios.get(`${url}?page=${page}`);
    
    // Use Cheerio for parsing HTML and extracting data
    const $ = cheerio.load(response.data);
    const data = $('.element-class').text();
    
    // Process the extracted data
    console.log(`Data from Page ${page}: ${data}`);
}
πŸ’‘
You need to install both axios & cheerio

$ npm i -s axios cheerio

Use a loop with web scraping libraries like Cheerio to extract data from multiple pages.


Looping with Batch Processing

const batchSize = 3;
const data = [/* large array of data */];

// Loop through data in batches
for (let i = 0; i < data.length; i += batchSize) {
    const batch = data.slice(i, i + batchSize);
    
    // Process the current batch
    console.log('Processing Batch:', batch);
}

Implement batch processing using loops to handle large datasets efficiently.


Looping with Dynamic Interval

let interval = 1000; // Initial interval in milliseconds

// Loop with dynamic interval
const dynamicLoop = setInterval(() => {
    // Loop logic
    
    // Adjust the interval dynamically based on some condition
    if (/* some condition */) {
        clearInterval(dynamicLoop);
        interval = 500; // Set a new interval
        dynamicLoop = setInterval(/* loop logic */, interval);
    }
}, interval);

Create a loop with a dynamically changing interval for adaptive and responsive execution.


Enjoying our content? Your support keeps us going! πŸš€

Consider buying us a coffee to help fuel our creativity.