The below code console logs the correct title
const cars = [{ id: 1, title: 'Volkswagen' }, { id: 2, title: 'BMW' }, { id: 3, title: 'Audi' }];
function getCarName(set, val) {
for(let i = 0; i <= set.length; i++) {
if (set[i].id === val) {
return set[i].title;
}
};
}
console.log(getCarName(cars, 2));
The below code console logs "undefined" why?
const cars = [{ id: 1, title: 'Volkswagen' }, { id: 2, title: 'BMW' }, { id: 3, title: 'Audi' }];
function getCarName(set, val) {
set.forEach((x) => {
if (x.id === val) {
return x;
}
});
}
console.log(getCarName(cars, 2));