Testing Objects for Properties13

Testing Objects for Properties13
0

#1

Tell us what’s happening:

Well, checkProp returns “gift”, myObj.gift returns “pony” and myObj.checkProp returns nothing. Why is it so, can anybody help?

Your code so far


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

function checkObj(checkProp) {
  
  if (myObj.hasOwnProperty(checkProp)===true) {
    console.log(checkProp);
    console.log(myObj.gift);
    console.log(myObj.checkProp);
  } else {
    console.log ('Not found');
  }
  
}

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


Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 OPR/52.0.2871.40.

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


#2

Hey @4Nancy,
You don’t have to console.log() your result.
You will need to return your result.

Same goes for this one as well.


#3

Yeah, I know.
But console.log(myObj[checkProp]); works for some reason and console.log(myObj.checkProp); doesn’t


#4

The above is undefined, because there is no actual property named “checkProp” in myObj. When you use dot notation with an object, the actual property name you specify after the dot must exist in the object.

You might want to review the following challenges on accessing object properties to make sure you understand when you can use dot notation and when you must use bracket notation. Basically, you can always use bracket notation, but depending on the circumstance, you might be able to use dot notation instead.

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables


Accessing object properties with dot and bracket notation
#5

Now I see.

Thank you!