Checking for an object property

Tell us what’s happening:
In the Javascript Basics Exercise “Testing Objects for Properties”, the example given on the exercise is:

var myObj = {
  top: "hat",
  bottom: "pants"
myObj.hasOwnProperty("top");    // true
myObj.hasOwnProperty("middle"); // false

In the last two lines, it has "top" and "middle" on parentheses but on the exercise I did (exercise is below this paragraph), the checkProp part in the second line is not supposed to be in parentheses and the function won’t execute properly if there are parentheses. Why is this?

function checkObj(obj, checkProp) {
    return obj[checkProp];
  } else {
    return "Not Found";

Your browser information:

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

Challenge: Testing Objects for Properties

Link to the challenge:

My apologies, but is this the line you are talking about?

Yes that’s the line. I’m wondering why don’t we have to include parentheses? Is it because the input is a string?

you have the parenthesis there
do you mean the quotes? ""
it is because checkProp is a variable with a value of string, you do not write variables with quotes

() indicates to JavaScript to evaluate whatever is in the brackets. Most often, this means you’re calling a function. So in this case, JavaScript function call, and this function takes a property name:


“Does myObject have the property with the key "someKey"?”

[] indicates to JavaScript that you are accessing a property on an object (more specifically [] immediately preceded by an object or a reference to an object and with a string in the brackets). So JavaScript object access:


"Access the value of the property with the key "someKey" on the object myObject"

Because a variable is evaluated to whatever it’s value is, this is also a string in object access:

let myVariableKey = "myKey"

And in a function call:


I meant the quotes, sorry mixed the words there, my bad. Thanks for clarifying

I meant quotes instead of parentheses, but your elaborate response helped me learn a lot about brackets, parentheses and quotes. Thanks.

1 Like