Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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 answers
Answer question

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 Report

0

b is optional, it is the index of the element

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!