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