Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
JavaScript reduce method behaving strangely when we pass a function with one argument

JavaScript noob here. I've got no clue how the map1 is calculated, I've changed every element of array1 one at a time, and map1 still prints as -8. Has anyone got any link to a detailed explanation of the reduce() method? I've found none! Or can anyone please explain what's happening?

const array1 = [1, 4, 9, 16];
const map1 = array1.reduce(x => x - 2, 0);
console.log(map1); // shows -8
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Nothing strange here. Look to docs.

What are you passing here is previousValue (or accumulator) with inital value as 0. Every iteration you just ignore elements from array and return previousValue - 2. Here are 4 iterations so returned value is -8.

about 4 years ago · Juan Pablo Isaza Relatório

0

In Javascript,reduce accepts

  • a callback function as first argument.
  • an initial value for accumulator as second argument
array1.reduce(() => {}, initialValue);

This callback has mainly two parameters

  • first param = accumulator
  • second param = current value

Accumulator is just like a box which get whatever value is returned from a previous iteration. We can use this to add things from every single iteration.

So lets see a basic example:

const initialValue = 0
const answer = [1,2,3,4].reduce((acc, curr) => {

}, initialValue);
console.log('answer: ', answer);

Here we have callback function which returns nothing.

Let's see the code execution flow for this example

For the first iteration, accumulator is set to 0, Since we aren't return anything, undefined is being returned from every iteration which sets acc = undefined on every iteration.

when all 4 iterations are completed, that accumulator is returned. (which is undefined in this case)

Example 2:

const initialValue = 0
const answer = [1,2,3,4].reduce((acc, curr) => {
    return acc - 2; 
}, initialValue);
console.log('answer: ', answer);

In First Iteration, acc = 0 due to initial value but at the end of this iteration, it return a value which is 0-2 = -2. acc is set to -2.

second iteration, acc-2 becomes -2-2 = -4.

third iteration, acc-2 becomes -4-2 = -6.

fourth iteration, acc-2 becomes -6-2 = -8. (last iteration, so `acc is returned and we get -8 as final result)

since we are using arrow functions, you can remove the brackets '{' '}' and 'return' keyword by writing it in single line as

const initialValue = 0
const answer = [1,2,3,4].reduce((acc, curr) => acc - 2 , initialValue);
console.log('answer: ', answer);

Both of the last two code are exactly the same with only the difference of syntactic sugar.

Hope this helps, have any questions please ask.

about 4 years ago · Juan Pablo Isaza Relatório

0

So put it simply, reduce takes in multiple values. First one being the previous value(in this case 0), second is the comparable value(newValue), then comes index and array.

const map1 = array1.reduce((prevValue, newValue) => newValue - 2, 0);

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda