Using for loop
IntuitionFirst, I used an if statement to check if nums.length is greater than 0. If it's not, then return init. Then, I created a variable called val to store
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
First, I used an `if` statement to check if `nums.length` is greater than `0`. If it's not, then return `init`. Then, I created a variable called `val` to store the output of the reducer function `fn`. I assigned an initial value of `0` to the val variable. Next, I used a `for` loop to iterate over every element in the `nums` array. For each element, I let it equal `val` and then set `init` to be the same as the value of `val` because, in every subsequent computation, `init` needs to be equal to the previous result, which is `val`. Once the `for` loop finishes (when it becomes `=` to `nums.length`), I returned the latest value of `val` from the loop.

I hope this clarifies things! Let me know if you need further explanations. 😊

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
**Time Complexity: O(n)**
The code iterates through the nums array once using a for loop. The number of operations inside the loop is directly proportional to the length of the array. Therefore, the time complexity is linear, denoted as O(n), where n is the length of the nums array.

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
**Space Complexity: O(1)**
The code uses a fixed amount of extra space regardless of the input size. It declares a few variables (val, i) and uses some constant space for operations. This extra space doesn't scale with the size of the input array. Therefore, the space complexity is constant, denoted as O(1).
# Code
```javascript []
/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function (nums, fn, init) {
    if (nums.length > 0){
        let val = 0
        for (let i = 0; i < nums.length; ++i){
            val = fn(init,nums[i])
            init = val
        }
        return val
    }
    else {
        return init
    }
};
```
['JavaScript']