Re-creating the Lodash Library: _.findKey()

Hi There!

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/pjs-javascript-capstone/projects/lodash

I’ve got this one working but I want to understand the logic behind something. I feel like I may be missing something obvious. This is the solution, that works as expected.

  findKey(object, predicate) {
    for (let key in object) {
      let value = object[key];
      let predicateReturnValue = predicate(value);
      if (predicateReturnValue) {
        return key;
        }
      }
      return undefined;
    }

The question I’ve got is - you’re explicitly told that “return undefined” has to fall outside of the loop.

Outside of the loop, return undefined to address all cases where no truthy values were returned from predicate.

My first pass, which succeeded and passed the test had the “return undefined” come as part of the if statement. IE:

  findKey(object, predicate) {
    for (let key in object) {
      let value = object[key];
      let predicateReturnValue = predicate(value);
      if (predicateReturnValue) {
        return key;
        } else {
          return undefined;
        }
      }
    }

That worked fine, but going back to look at the actual solution has gotten me confused.

If you “return undefined” outside of the loop, specifically the if statement, wouldn’t that mean that undefined will always be returned, overwriting return key in the case of a truthy response to predicateReturnValue?

Definitely feel like I’m missing something obvious here!

By returning a value, you automatically exit a function, so if you reach the end of a function, it means that nothing has been returned up to this point: This is a common way to save yourself lines of code (and unnecessary conditionals).

You know, logically, that by the time you reach the end of the function (after the loop), that no key value has been returned (because the code is still running). Since that’s the case, you can just return undefined.

1 Like

Ahhh perfect, that makes sense. Thanks!