Why property isn't accessible using dot?

I was stripping out the code to make it run and encountered a question when I want to access the property with a . (dot) it gives me undefined but when I use [checkProp], it prints out the correct value. why?

 function checkObj(obj, checkProp) {
  // Only change code below this line
  //return "Change Me!";
    if(obj.hasOwnProperty(checkProp)){
      console.log(obj[checkProp])
    console.log(obj[checkProp]) //returns undefined
    }

  // Only change code above this line
}

checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift") 
     

function checkObj(obj, checkProp) {
// Only change code below this line
//return "Change Me!";
for(let prop in obj){
  if(obj[prop].hasOwnProperty(checkProp)){
    console.log(obj[prop].checkProp)
  }else{
    return "Not Found"
  }
}
// Only change code above this line
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Testing Objects for Properties

Link to the challenge:

The hasOwnProperty method is used to check if a property exists in an object. In this case, you are calling it on obj[prop]. While obj is an object, obj[prop] is not.

Likewise, in console.log(obj[prop].checkProp), even if obj[prop] was an object (which it is not), you are attempting to reference an actually property named “checkProp”. None of the test cases pass in objects with properties named “checkProp”.

You should review the following three challenges as a refresher on the various ways to access an object’s properties. The method used depends on the property name and/or if the property name is being referenced as a variable or not.

1 Like

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