Testing Objects for Properties: what's wrong with my code?

Tell us what’s happening:

Your code so far


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

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

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties

the ‘dot’ syntax you are using is the problem
you can use the dot syntax if you want to access a known property like
myObj.gift
myObj.pet
myObj.bed

but since checkProp is not the actual literal name of any property, you have to use the bracket notation instead

myObj[checkProp]

3 Likes

Thanks, I have already sorted it

2 Likes

Thanks! 1st post I found that states why it will not work that I have found. I want to learn more about this particular topic. I have been learning off this site and w3schools.c0m but have not found an explanation for this. (might just be missing it). Can you please point me to an on line source where I can learn more about it?

2 Likes

Hi @RunningDad, welcome to the forum!

Here is a link to some Mozilla Developer Network documentation on Object Property Accessors which provides the details you seek.

Keep in mind that where it says…

In the object[property_name] syntax, the property_name is just a string or Symbol. So, it can be any string, including '1foo' , '!bar!' , or even ' ' (a space).

…this also means that any variable which holds a value of a String or Symbol can be used within the brackets (not just a string literal). So, as an example, both of the object property references in the sample code below are equivalent:

let foo = { bar: 1 };
let prop = 'bar';

console.log(foo['bar']); // Output to console: 1
// The above object property reference is equivalent to the one below...
console.log(foo[prop]); // Output to console: 1
1 Like

Thank you for a great and quick reply!