Stuck on "Testing Objects for Properties"

Can’t seem to pass this one. It tells me “myObj is not a function”. Why doe myObject have to be a function? Don’t get it.

TIA,

Gabriel

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

function checkObj(checkProp) {
  // Your Code Here
  if (myObj.hasOwnProperty(checkProp) === false) {
    return "Not found";
  } else if (myObj.hasOwnProperty(checkProp) === true)
  return myObj(checkProp);
}

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

I already had:
return myObj(checkProp);

Seems like it should take it, not sure why it doesn’t.

another hint: look back to the 3 “Accessing Objects Properties with…” exercises.

1 Like

If you wanted to check properties of an object you should pass the object to the function. Anyway, functions are data types in Javascript so you can attach them to objects. This will do the trick

// Setup
var myObj = {
gift: “pony”,
pet: “kitten”,
bed: “sleigh”,
checkObj : function(prop){
if(this.hasOwnProperty(prop)){
return this[prop];
} else {
return “Not found”;
}
}
};

alert(myObj.checkObj(“gifty”));

This way function is attached to an object so it can be called directly on object to check if property exists. Sorry about indent though. There is also another way to solve this but I think this is the common practice and recommended one.

And to correct code as is in your case would be

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

function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp) === false) {
	return "Not found";
} else if (myObj.hasOwnProperty(checkProp) === true){
	
// return myObj(checkProp); - here you return non-existing function call, myObj is an object not a function and checkObj(checkProp) is a proper function call
    return myObj[checkProp];
}

}

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

It took me a while but I finally got it. This is what finally took:

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

function checkObj(checkProp) {
  // Your Code Here
  if (myObj.hasOwnProperty(checkProp) === false) {
    return "Not Found";
  } else if (myObj.hasOwnProperty(checkProp) === true)
  return myObj[checkProp];
}

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

This is the shortest answer:

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

function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp)){
return myObj[checkProp];
}
return “Not Found”;
}

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