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

111
Visualizações
JavaScript's forEach method taking a function as a parameter that takes an argument that seems it has no role

I've encountered with this piece of code in a book I'm reading, and I couldn't understand what the b argument that is defined in the function inside the forEach method does.

Here's the source code:

var tab = [2, 3, 5];
tab.map(x => x + 3)
   .filter(x => x > 5)
   .forEach(function(a,b){console.log(a-3);});
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Okay, I've dug a bit deeper and found out that the function inside the forEach() method can take up to 3 arguments, so the function can be written like this: forEach(function(a, b, c) { // Instructions }); with a being the element of the current iteration, b being the index of that element and c being the array itself.

Example:

const samples = ['sample_1', 'sample_2', 'sample_3'];
samples.forEach(function(a, b, c){
    console.log(a); // shows the element
    console.log(b); // shows the index of the element
    console.log(c); // shows the whole array
    console.log('Onto the next sample.')
});

In this example, on the first iteration, a will be 'sample_1' b will be 0 and c will be the whole array. Second iteration, a is 'sample_2', b will be 1 and c will be the whole array. And so on with all the remaining iterations. Note that the function inside the forEach() method takes only 3 arguments, not more.

about 4 years ago · Juan Pablo Isaza Relatório

0

b is optional, it is the index of the element

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