Testing object for properties [Solved]

Testing object for properties [Solved]
0

#1

In this component why doesn’t this code return the correct result when using dot notation. No problems when I use bracket notation however, but was just wondering what is wrong with my code for dot notation.

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

function checkObj(checkProp) {
// Your Code Here
var objAns = myObj.hasOwnProperty(checkProp);

if (objAns){
return myObj.checkProp;
}
return “Not Found”;
}

// Test your code by modifying these values
checkObj(“gift”);


#2

In your code, myObj.checkProp (dot notation) looks for a property in your object that’s literally named checkProp. It fails because myObj has no checkProp property, only gift, pet, and bed.

When you use myObj[checkProp] (bracket notation), checkProp is substituted with the value contained in the variable checkProp, so it is evaluated to, say, myObj['gift'], or myObj['pet'].

In short, dot notation is useful when you know the name of the property you want to access, and bracket notation for dynamically accessing a property of an object.


What is the difference? 1 works 2 doesn't!
Access an object with dot property
#3

@kevcomedia great explanation, this helped me also. Thanks!