Testing Objects for Properties_2

Tell us what’s happening:
Once again, I’m having trouble with the logic. First, I wasn’t sure whether to put quotes within the hasOwnProperty function. (method) When I removed the quotes, I kept getting undefined, so I put them back. The return value with quotes is always Not Found.

Your code so far


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

function checkObj(checkProp) {
 if(myObj.hasOwnProperty("checkProp"))   
{
   return myObj.checkProp;
 } 
  
  return "Not Found";
}

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

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

/* TEST RESULTS
// running test
checkObj(“gift”) should return “pony”.
checkObj(“pet”) should return “kitten”.
// tests completed
*/
Your browser information:

User Agent is: Chrome/68.0.3440.75 .

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

When you write myObj.hasOwnProperty(“checkProp”), you are asking if myObj has an actual property named “checkProp”. Remember, checkProp is a variable. It contains a string, so you can just reference checkProp without the quotes around it.

You can not use dot notation to access an object’s property with a variable. Review your previous lessons on how to do this properly.

This is what I did, and it worked, but I have a couple of questions:

  1. Is this the best way to do this lesson? It seems like you should be able to put checkProp directly in the brackets since both checkProp, v1, & v2 are all variables. Any explanation for this? Thank you for your help.

‘’’
// Setup
var myObj = {
gift: “pony”,
pet: “kitten”,
bed: “sleigh”
};

function checkObj(checkProp) {
if(myObj.hasOwnProperty(checkProp)){
var v1 = checkProp;
var v2 = myObj[v1];
return v2;
}

return "Not Found";

}

// Test your code by modifying these values
console.log(checkObj(“pet”));
‘’’

if you did myObj[checkProp] I believe it returns undefined if the object doesn’t exist.

I know that but why?? Thanks for the reply.

Not sure how to answer it other than to say because it doesn’t exist. If js doesn’t find something to return, it usually returns an undefined or something similar.

I will say that you should google “falsy javascript”. It may help answer your questions.

Okay, thanks. (bla, bla.)