0

I have the following two functions that should be doing the same thing. The first function getProductIndex(id) returns 2. The second function getProductIndex2(id) returns undefined. The only difference is the placement of the return statement. Why is the function returning undefined if the return statement is inside the if statement?

function getProductIndex(id) {
  let num = "";
  products.forEach(function(item, index) {
    if (item["productId"] === id) {
      num = index;
    }
  })
  return num;
}

function getProductIndex2(id) {
  products.forEach(function(item, index) {
    if (item["productId"] === id) {
      return index;
    }
  })
}

console.log(getProductIndex(102));
console.log(getProductIndex2(102));

returns (2 is the correct index, FYI):

(base) j@joshs-mbp-2 javascript % node practice.js
2
undefined
jpanknin
  • 115
  • 2
  • 3
  • 11
  • 5
    `forEach` doesn't use or return anything. use `.find` or `findIndex` – Daniel A. White May 29 '23 at 23:04
  • 2
    You're not returning anything in the function `getProductIndex2`, you're returning in the callback function you pass to `forEach` – Lennholm May 29 '23 at 23:11
  • @MichaelLiu i did not flag this as a dupe – Daniel A. White May 29 '23 at 23:14
  • @Lennholm got it. So how would I get the value back with the ```getProductIndex2``` approach? – jpanknin May 29 '23 at 23:19
  • 2
    there is absolutely no way to get the value with `getProductIndex2` approach - you would have to rewrite it (i.e. use a *different* approach) using `.findIndex` as suggested in the first comment – Jaromanda X May 29 '23 at 23:38
  • @jpanknin As long as you're using `forEach` it won't work because `forEach` ignores any returned value and doesn't return anything to the caller. So, as others have pointed out, use `findIndex`, which does return a result to the caller. If you want to use `forEach` you have to go with your first approach but `findIndex` is better since it exists for this exact purpose. – Lennholm May 30 '23 at 17:40

0 Answers0