Basic JavaScript - Testing Objects for Properties

Tell us what’s happening:
Describe your issue in detail here.

I found this code in the hint section of this lesson , It works but i dont understand why it works.

function checkObj(obj, checkProp) {
// Only change code below this line
if (obj.hasOwnProperty(checkProp)) {
  return obj[checkProp];
} else { 
  return "Not Found";
}

**i just do not understand how it correlates to the subject, how to get to this code in relation to the questions asked.** 

* `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return the string `pony`.

* Passed:`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return the string `kitten`.

* Passed:`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return the string `Not Found`.

* Passed:`checkObj({city: "Seattle"}, "city")` should return the string `Seattle`.

* Passed:`checkObj({city: "Seattle"}, "district")` should return the string `Not Found`.

* Passed:`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return the string `Not Found`.

The object list is nowhere to be found so on what is this code checking its validdity?

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 Edg/103.0.1264.77</code>

**Challenge:**  Basic JavaScript - Testing Objects for Properties

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

Try talking through the function and explaining what it does at each step.

The .hasOwnProperty() is a JS in-built Object method that takes one argument; the property’s name and returns a boolean to indicate whether or not the given property is present in an object.

The checkObj function takes in two arguments; the Object and a property name. The if-else block then uses the boolean value from the .hasOwnProperty() method to determine if the function returns the value of a property (when true) or ‘Not Found’ (when false)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.