Access objektu property with dot operator vs brackets

Hello.

Today I started JS objects
And here I solved such issue

Instructions
Modify the function checkObj to test myObj for checkProp. If the property is found, return that property’s value. If not, return “Not Found”.

And here is my solution

// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};
function checkObj(checkProp) {
  // Your Code Here
  if(myObj.hasOwnProperty(checkProp) == true){
   return myObj[checkProp];
  }else{
  return "Not Found";
  }
}

But at first I try to do it ** return myObj[checkProp];**
With dot operator but it doesn’t work.
Why? In the previous chapter I read that brackets notation is useful when property have two or more words. Isn’t it correct?

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

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

If the property name has spaces, you can not use dot notation and must use bracket notation. If you are using a variable for the property name, then you must also use bracket notation.

Can you show us the code you tried with dot notation that did not work? I am not sure how you were trying to use it.

1 Like

Thanks I realized
. I have used variable for the property name
My code with dot operator

<p>
// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};
function checkObj(checkProp) {
  // Your Code Here  
 if(myObj.hasOwnProperty(checkProp) == true){
   return myObj.checkProp;
  }else{
  return "Not Found";
  }
}
// Test your code by modifying these values
checkObj("gift");
</p>