Testing Objects for Properties dot notation not working

Tell us what’s happening:
This code works, but I don’t know why dot notation doesn’t work in this instance. Can anyone explain?

Your code so far

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

function checkObj(checkProp) {
  // Your Code Here
  myObj.hasOwnProperty(checkProp);
  if (myObj.hasOwnProperty(checkProp) == true) {
    return myObj[checkProp];   //why doesn't dot notation work here: myObj.checkProp; ??
  } else {
  return "Not Found";
  }
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/testing-objects-for-properties

Review Accessing Objects Properties Using Dot Notation and Accessing Objects Properties with Bracket Notation:

There are two ways to access the properties of an object: the dot operator (.) and bracket notation ([]), similar to an array.
The dot operator is what you use when you know the name of the property you’re trying to access ahead of time.

3 Likes

So since the variable that represents the property needing to be accessed is not specific, only bracket notation would work in this instance? Thank you for the quick response.

You got it!

Looks like I took too long posting this, but I will just leave this here just in case it still helps.

Dot notation is useful for grabbing key-value pairs out of an object.

var myObj = {
  keyTwo: valueOne,
  keyOne: valueTwo,
  keyThree: valueThree
}
console.log(myObj.keyOne);  // outputs 'valueOne'
console.log(myObj.keyTwo);  // outputs 'valueTwo'
console.log(myObj.keyThree);  // outputs 'valueThree'

However, what if I am trying to reference key-values through a variable?

var thisVariable = keyOne;
console.log(myObj.thisVariable);  // there is no key 'thisVariable' in 'myObj'
console.log(myObj[thisVariable]);  // outputs 'valueOne' as expected

Bracket notation saves the day as the thisVariable expands into keyOne. Bracket notation is also needed if your key values have spaces in them.

1 Like

Both responses make this very clear. Thank you both.

Thanks ArielLeslie. I’ve been wondering about this 5 minutes ago.

thank u so much it helps me