Testing Objects for Properties (Question)

Can anyone explain me why in this challenge the return for the if must be

 return myObj[checkProp];

but If I use:

return myObj.checkProp;

It doesn’t work


Your code so far

// 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";

  return "Change Me!";

// Test your code by modifying these values

Look at the value you’re passing for checkProp - it’s a string. So, using dot notation would give you myObj."gift". However, if you look at the properties of myObj, they’re not written as strings. Just for fun, do console.log(myObj.gift), and then console.log(myObj."gift").
Anyway, if you have to pass in a property as a string here, use bracket notation.

1 Like

Be careful there, dot notation want an exact match to the property name, if you have a variable that holds the property name you want to always use bracket notation

The simple answer is because checkProp is a variable and dot notation cannot use variables, only square brackets can.

Yes, your point is the most meaningful one in this thread, and should be checked as the best solution.