1

In the following code, the function findById() does not actually return anything. The console.log()s fire and print as expected but the result is that the variable the function is being called to is undefined.

I have tried to change return value types, even simply putting return true; at the end with no conditional, but it always is undefined. To make sure I was not missing something simple I actually created a function that only returns a value istrue(). This actually works fine.

This is the object/method def

const database = {
    // List of authenticated characters
    characters: [],
    addCharacter: function(c) {
        this.characters.push(c);
    },
    findById: function(id) {
        console.log('Searching for character...');
        this.characters.forEach((c) => {
            if (c.id === id) {
                console.log('Found');
                console.log('cid: ' + c.id);
                console.log('id: ' + id);
                return true; // Never actually returns
            }
        });
    },
    istrue: function() {
        return true;
    }
};

and where it is being called

const find = database.findById(characterIdToFind);
console.log(typeof find); // always undefined
console.log(find); // always undefined

I expect there to be some kind of return value in at least one of the permutations of this function I have tried. There is never any change in the return value of the function, simply undefined.

twodox
  • 155
  • 8
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach - return `undefined` – random May 17 '19 at 03:59
  • @randomSoul the return value of `forEach` is irrelevant here. The fact is, `return true;` returns *from the callback*, not from `findById`. And `findById` has no return value itself. You'd get the same result it using `.map`, or `.some` instead of `.forEach`. – VLAZ May 17 '19 at 04:16
  • Possible duplicate of [What does \`return\` keyword mean inside \`forEach\` function?](https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function) – VLAZ May 17 '19 at 04:18

2 Answers2

4

The return statement inside a nested function return from function.

In this case you could use some() instead of forEach() because you can't break forEach.

findById: function(id) {
    console.log('Searching for character...');
    return this.characters.some(c => c.id === id)
}

If you want to get the object which matches the given condition that use find()

findById: function(id) {
    console.log('Searching for character...');
    return this.characters.find(c => c.id === id)
}

If you see in above both method we are returning c.id === id implicitly in each iteration but it doesn't return from outer function.

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
3

This is because you are trying to return from forEach & forEach does not return anything

brk
  • 48,835
  • 10
  • 56
  • 78