Array Reduce Transformation: JS Clear Explanations with Code Examples
DescriptionThis implementation of reduce replicates the functionality of the built-in Array.prototype.reduce method. It takes an array, a callback function, and
# Description
This implementation of `reduce` replicates the functionality of the built-in `Array.prototype.reduce` method. It takes an array, a callback function, and an initial value, then iterates over the array to produce a single accumulated result. The function demonstrates key JavaScript concepts such as higher-order functions, iteration, and immutability.

# Key Concepts:
- **Higher-order functions:** Functions that accept other functions as arguments or return functions.
- **Callback functions:** A function passed as an argument to another function, executed during the iteration.
- **Iteration (for-of loop):** A clean and concise way to iterate over arrays in JavaScript.
- **Immutability:** The initial value (init) is updated but does not mutate the original array.
- **Return statement:** Used to return the final accumulated value.

# Code
```javascript []
var reduce = (nums, fn, init) => {
    for (const num of nums) init = fn(init, num);
    return init;
};

```

# Code With Comments
```javascript []
/**
 * Custom reduce function implementation.
 * @param {number[]} nums - Array of numbers to iterate over.
 * @param {Function} fn - Callback function to process each element.
 * @param {number} init - Initial value for the accumulator.
 * @return {number} - Final accumulated value.
 */

var reduce = (nums, fn, init) => {
    // Iteration (for-of loop): Loops through each element in the array.
    for (const num of nums) {
        // Callback function: 'fn' processes the current accumulator and array element.
        init = fn(init, num); // Immutability: 'init' is updated without modifying the array.
    }
    // Return statement: Returns the final accumulated value.
    return init;
};

/**
 * Example usage:
 */
const nums = [1, 2, 3, 4];
const sum = reduce(nums, (acc, curr) => acc + curr, 0); // Higher-order function: Passes a callback to 'reduce'.
console.log(sum); // Output: 10
```

['JavaScript']