findKey() - recreating Lodash Library


#1

Hi guys, I just got stuck at this task https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/pjs-javascript-capstone/projects/lodash (task 29 point 5) which is:

“Still within the loop, create another variable called predicateReturnValue and set it equal to the result of calling predicate with value .”

This is my code and it doesn’t work. I know it’s a mess. Please, help.

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


#2

Okay, I know where the problem was:
To my surprise everything was OK until the if statement. It should go like this:

if (predicateReturnValue) {
      return key
      };
    }
      return;
}   

But I still don’t get it why the truthy value is checked in this way.
Could anyone explain?


#3

The conditional expression will always yield a boolean.

if ('a' === 'A'.toLowerCase())

can be interpreted as,

if (true)

since the resulting boolean of the above will be true.

if (truthy) {

} else {
    // must not be truthy
}

We need never compare a conditional expression to true. It is already that by virtue of its truthiness, and will toggle to the opposite boolean if not. if () and while () can only ever yield true or false from their condition.

We can boil your code down to this simple method…

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

Note that we don’t even need the final return. No return will be interpreted as undefined.


#4

Thank you very much for your reply. I must think about it for like an hour hahahah :slight_smile: Greetings from Poland mtf :slight_smile: