Strings with hasOwnProperty

How come in the example, we use a string to check against the properties that exist it works. But if we fetch checkProp as a string in the final solution, it doesn’t work.

Example

const myObj = {
  top: "hat",
  bottom: "pants"
};

myObj.hasOwnProperty("top");
myObj.hasOwnProperty("middle");

Solution that gives Error as “checkProp” and Correct as checkProp

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
}

Challenge: Basic JavaScript - Testing Objects for Properties

Link to the challenge:

This code reads within the obj look for a string checkProp, remember checkProp is a variable which is carrying a string value. This code is literally looking for checkProp within your object.

1 Like
const obj = {
  name: 'Colin',
}

const checkProp = "name";

// true because obj has a "name" property
obj.hasOwnProperty("name")

// true because checkProp evaluates to "name"
// and obj has a "name" property
obj.hasOwnProperty(checkProp)

// false because obj does not have a "checkProp" property
obj.hasOwnProperty("checkProp")
1 Like

without quotation marks, program test includes quotes

if (obj.hasOwnProperty(checkProp)){ …}

Hi, let me see if I can explain it with a little more detail, and the answers before are super helpful to follow along with as well!

Here’s your code below:

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
}

So, in the very beginning, you made a function called checkObj - spot on. In that function, you’re passing through two arguments, that could be anything - numbers, strings, boolean, etc. In this case, you’re going to pass through 2 values, and you’re labeling them as the variables ‘obj’ and ‘checkProp’.

The if loop comes in so you can start looping through your data/array, and locating what you’re looking for. In this case, you’re trying to locate a certain property, right? For example, you’re checking if myObj has the properties you pass through. Perfect. However, check out how you wrote “check Property” in quotations. That means that now the function is literally looking for the string “check Property” instead of the value you assigned to it/the variable of checkProp.

Also, one last thing! You need to make sure you include that little semicolon after the string “Not Found” or JavaScript won’t read the rest of the directions to execute in this if function.

I hope this helps you. Good question! :slight_smile: