Home > Back-end >  Why map or reduce keeps running without any condition given?
Why map or reduce keeps running without any condition given?

Time:02-13

const array = [7, 2, 4, 1, 10, 6, 5, 11]

const max = array.reduce((acc, val) => {
    console.log(val, acc)
    
    return val > acc ? val : acc
}, 0)

console.log(max)

I was looking at this code of reduce array method, one thing I couldn't understand at all is, How the reducer function is going to the next iteration? There is no condition that forces the reducer function to go to the next element in the array. In the first iteration, the val is 7, the first element of the array, and acc is 0, the reducer function returns 7 as per the condition written. My question is how the number 7 as being the new accumulator is going to be called on the reducer function. I thought the normal procedure is you have to meet some kind of condition to iterate over again and again. Is there something written in the reduce method itself? Can you explain me please?

CodePudding user response:

Note that array.reduce:

reduce calls the callback, as a function, once for each element after the first element present in the array, in ascending order.

You could understand the reduce as a array.map but the goal of it is to change the array to a singe output.

It will loop over the whole array same with the forEach/map/...

Check below example, even though you don't do anything, like return or anything else to array.reduce, it will still work and iterate the array

You could check here for more

But of course if you don't use return for array.reduce, there will be no benefit for you to use it.

const array = [7, 2, 4, 1, 10, 6, 5, 11]

const max = array.reduce((acc, val) => {
  console.log(val)
}, 0)

console.log(max)

CodePudding user response:

As per the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

The reduce() method executes a user-supplied “reducer” callback function on each element of the array,

CodePudding user response:

The reduce method's implementation resembles something like this:

Array.prototype.reduce = function(callback, initialValue) {
    var acc = initialValue;
    for(var i = 0; i < this.length; i  ) {
        acc = callback(acc, this[i], i);
    }
    return acc;
}

The reduce methods iteration condition is the array length. The same goes for map.

  • Related