Testing Objects for Properties - What The Eff

So I’ve completed this challenge. I still don’t really understand it. I even read over this page to try to get a better understanding. I google searched and found out ways other people do it and I looked at so many I think that’s actually the only reason I was able to solve it. I tried for the longest time to solve it without looking at anyone else’s answers and even after I still don’t quite understand it. I am ashamed to admit how long it took me to solve this challenge. I feel like the examples for this challenge were bad/misleading and it has been the hardest so far. Can anyone direct me to other material that I can read on this subject or give me other examples of its use so I may wrap my head around it?

Your code so far


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

function checkObj(checkProp) {
  // Your Code Here
  if (myObj.hasOwnProperty(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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

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

Hey @MrTStephenson,
What is the thing that you do not understand?
I will still try to explain
Let me walk you through step by step:
1) First myObj is an object which is already declared and given here.

2) Now we have to write a function checkObj() with argument checkProp to check whether checkProp property exits in the myObj.

3) We write a if statement to check if checkProp exists in myObj and if yes return name of that property.

Notice we are using hasOwnProperty() method here ,which checks for property inside an object.

For example, if you are checking if myObj has “gift” property in it, then function should return “gift”. Else return “Not found”.

Hope this helps.

1 Like

The checkObj function is checking whether the function parameter, i.e checkProp exist as property in the myObj object.

if (myObj.hasOwnProperty(checkProp)) 

The above ‘if’ condition iterate through all the properties of myObj , if the property checkProp exist, then it returns true otherwise Not Found.

The hasOwnProperty() is a method available in Object.prototype which is use to check the availability/existence of the property in the Object you are trying to check. The method returns boolean values true or false

You can read more about it here.

1 Like

I appreciate you all laying this out for me. This helps a lot. I think I had been studying for too long yesterday and my brain was in a complete fog. This info helps a lot.