Confused about "" and [] when calling property

Tell us what’s happening:
quick question: why the code:
return obj.checkProp
won’t work? and why it has to be:
return obj[checkProp]
in what situation should you use which method to call a property?
I am a bit confused. Thanks!!

Your code so far


function checkObj(obj, checkProp) {
// Only change code below this line
if (obj.hasOwnProperty(checkProp)){
  return obj[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_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.

Challenge: Testing Objects for Properties

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it 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.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

Hey, I know it may have been a while ago, but there is a lesson specifically about this:

1 Like

Hello there.

This is because the checkProp variable is exactly that - a variable.

obj.checkProp looks for the property checkProp in the object obj.
obj[checkProp] looks for the property with the value of checkProp in the object obj.

obj.checkProp is the same as obj["checkProp"].

Hope this helps

4 Likes

Please keep in mind that this notation is used when you have an object that is composed of two words e.g (my object). if it is only one word then you can use the . syntax.
In the specific example you stated remember that checkprop is not the actual value of the property. it stands for a variable that contains the property value, i guess in this circumstance using the is the rule .
anyone can correct me if i am wrong

Please keep in mind that this notation is used when you have an object that is composed of two words e.g (my object). if it is only one word then you can use the syntax.
In the specific example you stated remember that checkprop is not the actual value of the property. it stands for a variable that contains the property value, i guess in this circumstance using the is the rule .
anyone can correct me if i am wrong

This is without a doubt the most succinct way to describe this answer.

If you want to read more about dot notation versus bracket notation there is a good article here.

1 Like