Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I utilize the index for my callback?

Going through some practice problems and can’t figure out how correctly callback. It returns "

let myForEach = function(array, cb) {
  for (let j = 0; j < array.length; j++) {
    cb(array[j])
  }
};

myForEach(['a', 'b', 'c'], function(el, i) {
  console.log(el + ' is at index ' + i);
});


// expected return "a is at index 1"
// actual return "a is at index undefined"

I tried to call i as an extra argument, and tried to use this.i, call it within the scope of the cb, all either return undefined or are ignored.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can utilize the index for the callback by passing it in as a second argument:

let myForEach = function(array, cb) {
  for (let j = 0; j < array.length; j++) {
    cb(array[j], j)
  }
};

myForEach(['a', 'b', 'c'], function(el, i) {
  console.log(el + ' is at index ' + i);
});

// expected return "a is at index 0"
// actual return "a is at index 0"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading