Testing Objects for Properties (Need Help!)

Hello everyone, i need some help.
While my code pass the test, i don’t use .hasOwnProperty as in instruction, now I’m confused why my code passed.
Can someone kindly explain it?

Is the best practice to check existing property use .hasOwnProperty or not?

sorry for broken english


// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};

function checkObj(checkProp) {
  // Your Code Here
  if(myObj[checkProp]) {
    return myObj[checkProp];
  } else {
      return "Not Found";
  }

}

// Test your code by modifying these values
checkObj("gift");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties

What if myObj[checkProp] is a falsy value like false or 0? Granted it never happens in this trivial example, but you want to keep that in mind for future code.

Your code passed because the tests aren’t written very strictly, and are only testing the outputs of checkObj rather than ensuring you used .hasOwnProperty. I’d say it’s a bug in the tests, or at least a deficiency.

1 Like