function checkObj(obj, checkProp) {
if(obj.hasOwnProperty(checkProp)){
return obj.checkProp;
//return obj[checkProp]
}
return "Not Found";
}
This:
return obj.checkProp;
Is returning the value for a property called “checkProp”. That is not what you want, you want the value of the property whose name is stored in the variable checkProp. Does that make sense?
const myObj = {
foo: 'foo123',
checkProp: 'checkProp123',
}
const checkProp = 'foo'
console.log(myObj.checkProp)
// checkProp123
console.log(myObj['checkProp'])
// checkProp123
console.log(myObj[checkProp])
// foo123
console.log(myObj.foo)
// foo123
console.log(myObj['foo'])
// foo123
Normally we use dot notation as a default. There are two cases when you must use bracket notation:
- The property name is in a variable.
- The property name is not a valid JS identifier, i.e., a string containing alpha numeric, _, or $, and not starting with a number.
I think I got it.
So, when I say myObj.checkProp
or myObj['checkProp']
, I am accessing the value of the property checkProp
in the myObj object.
But when I say myObj[checkProp]
, I am first accessing the value held by the variable named checkProp
. Then, I take that value and check for a property name the same as that value. And finally, get the value inside that property.
Did I get it?
I thinks so. myObj.checkProp
or myObj['checkProp']
specifically looks for a property called “checkProp”. myObj[checkProp]
is looking for a property whose name is whatever is in the variable checkProp. If checkProp === "date"
, then it looks for a property called “date”, if checkProp === "numberOfElephants"
, then it checks for a property called “numberOfElephants”.
But when I say
myObj[checkProp]
, I am first accessing the value held by the variable namedcheckProp
. Then, I take that value and check for a property name the same as that value. And finally, get the value inside that property.
Sure, on a JS level, that’s probably about what is happening. In common usage, we just look at see that it is trying to evaluate to the value of whatever key is stored in that variable checkProp.
Don’t feel bad - a lot of people get confused on this as they are learning.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.