Testing Objects for Properties 101

Tell us what’s happening:

Your code so far

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

function checkObj(checkProp) {
  // Your Code Here
  return myObj["pet"];
  return myObj["gift"];
  return "Not Found";

// Test your code by modifying these values

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:

You are doing something wrong here.

Let’s break the problem down to make it easier:

You need to check whether a property exists (in this case: checkProp), what does that mean? it means two things:

  1. Conditions should be used (if (property exists) { do something } else { do something else })
  2. hasOwnProperty() method should be used to check whether the property exists.

It’s up to you now to find the solution based on this information.
If you have more questions, don’t hesitate to ask, I will be glad to help.

Now what’s the problem

When you’re accessing the object property that you already know exists, then you use dot notation - .
When you’re checking for properties of object, you’re not sure exists, then you use bracket notation - []

Read the assignment again and then look at my code below.

function checkObj(checkProp) {
  // Your Code Here
  if( myObj.hasOwnProperty(checkProp)){
    return myObj[checkProp];
  return "Not Found";
1 Like