0

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));
  • 6
    Your `return` in the `.forEach()` case is **inside** the callback, not the outer function. A `return` statement exits from a single function call. – Pointy Nov 19 '22 at 15:22
  • 1
    `set.find` is a more suitable approach – James Nov 19 '22 at 16:48

0 Answers0