Why can I only return value with [] and not with dot notation in this challenge?

Hello, Im not sure if I misunderstood something about Acessing Object Properties with boxy bracket- notation and dot-notation, or if it is just something specific to this challange. I would be grateful some some explanation as it’s puzzling my brain :smiley:

ASSIGNMENT: Testing Objects for Properties
Modify the function checkObj to test if an object passed to the function ( obj ) contains a specific property ( checkProp ). If the property is found, return that property’s value. If not, return "Not Found" .

MY SOLUTION:

function checkObj(obj, checkProp) {

  // Only change code below this line
  if (obj.hasOwnProperty(checkProp)) {
    return obj[checkProp]; //WHY DOES IT NOT PASS WITH:  return obj.checkProp;  ?
  } else {
    return "Not Found";
  }

  // Only change code above this line
}

Because obj.checkProp would be:

  • obj["checkProp"] (in bracket notation with quotes around checkProp)
  • not obj[checkProp] (no quotes)

So checkProp is the value of some variable checkProp, e.g. "hello",
but "checkProp" is the actual value "checkProp".

1 Like

When accessing a property with the . dot notation, you need to use the actual accessor key.

However, when using the [] bracket notation you will “evaluate” whatever value is passed an then use it as accessor, this is especially handy when you rely on a variable or a computed value.

For example:

var object = {
 foo: "bar"
};

// using dot notation I have to use the actual accessor value
object.foo // "bar"

// using bracket I can pass a variable
var myVariable = "f" + "o" + "o";
object[myVariable] // "bar"

Hope it helps :sparkles:

2 Likes
const obj = {
  checkProp: "someValue",
  foo: "bar"  
}

obj.checkProp  // evaluates to "someValue"
obj.foo        // evaluates to "bar"

const checkProp = "foo"
obj[checkProp] // evaluates to "bar"

const foo = "checkProp"
obj[foo]       // evaluates to "someValue"
1 Like

It totally makes sense now! Because I’m not trying to return the string “checkProp” but the value that [checkProp] holds. Thank you! I did not realize the difference. Glad I asked instead of letting it pass.

And also thank you for putting my code in the “code box” for me! I did not even know I could do that! :smiley: I will use it next time! :slight_smile:

1 Like

Thank you so much! I went back to my notes and with your input it makes more sense. :slight_smile: Thank you!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.