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
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
}
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"
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! I will use it next time!