Why does this function return undefined but console.logs the correct answer?
I have this function
const getMonthlyPriceFromData = (planName) => {
planTypeData.map((item) => {
if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
return item.monthlyFee;
}
return null;
});
};
when I console.log(item.monthyFee) it returns the correct answer but when I call
console.log(getMonthlyPriceFromData('Free')) it returns undefined?
Solution 1:
There is no actual return
statement inside your function:
const getMonthlyPriceFromData = (planName) => {
return planTypeData.map((item) => {
if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
return item.monthlyFee;
}
return null;
});
};
Or use short arrow form. This way you can omit the return
keyword, only if you skip the curly braces too {
:
const getMonthlyPriceFromData = (planName) => planTypeData.map((item) => {
if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
return item.monthlyFee;
}
return null;
})
EDIT:
OP seems to want only one item retuned from the array and for that find()
would be a better approach:
const getMonthlyPriceFromData = (planName) => planTypeData.find((item) => {
if (item.name === planName) { console.log(item.monthlyFee, 'fee')
return true; }
return false; })
Solution 2:
You need to add a "return" before "planTypeData.map", like this:
const getMonthlyPriceFromData = (planName) => {
return planTypeData.map((item) => {
if (item.name === planName) {
return item.monthlyFee;
}
return null;
});
};
console.log(getMonthlyPriceFromData('Free'))
Then it should work!