Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

b is optional, it is the index of the element

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda