From the freecodecamp video i am trying to follow on youtube i am trying
to understand why its [checkProp] instead of .checkProp i thought
that with objects it was dot annotation or with {} if the strings have spaces
in beyween
var myObj = {
‘gift’: ‘pony’,
‘pet’: ‘kitten’,
‘bed’: ‘sleigh’
};
function checkObj(checkProp) {
if(myObj.hasOwnProperty(checkProp)) {
**return myObj[checkProp]** ;
} else {
return 'none';
}
}
console.log(checkObj(‘bed’));
1 Like
salv236:
someObj[checkbox]
Here you are able to pass in a variable as the object key instead of specifying in code the key name obj.keyname
← cannot change
1 Like
in this case doesn’t checkProp represent the property name within the object myObj? i.e gift.
ILM
February 1, 2019, 3:44pm
4
Dot notation try to access literally a property of that name, bracket notation will evaluate what’s inside the brackets before accessing the property
1 Like
Here’s an easy way to understand it.
dot notation requires the property to match literally.
example
let car = {
“first”: “mustang”
};
console.log(car.first); // mustang
console.log(car["first"]); // mustang
That’s because “first” matches the key literally inside of the car object.
Now say you did this:
let car = {
"first": "mustang"
};
let variable = "first";
console.log(car.variable); // undefined
console.log(car[variable]); // mustang
That’s because .variable
is not a key inside of car. So you must use the square bracket to get the value of variable rather than the literal string variable.
1 Like
in this case doesn’t checkProp represent the property name within the object myObj? i.e gift.
Yes, correct. checkProp
is the variable inside the scope of the function
ok, i am slightly confused in my example shouldn’t it be literal matching as
the property we are trying to call is within the object?
Why would it be literally checking when you’re using square brackets? Did you read my post thoroughly?
return myObj[checkProp] ;
This object has a property with a key ‘gift’
This object has a property with a key ‘pet’
This object has a property with a key ‘bad’
var myObj = {
gift: ‘pony’,
pet: ‘kitten’,
bed: ‘sleigh’
};
This object does not have a property with a key ‘checkProp’
salv236
February 2, 2019, 10:31am
10
ok i think i have understood, it has to be an exact checkProp is an argument that
represents the property but not the exact property which is why myObj[checkProp]
is required.