When you loop over the object customer
, you are retrieving the keys one by one. The variable key
holds the property within the customer
object. So, accessing customer[key]['enjoysCoffee']
essentially means extracting the 'enjoysCoffee' property from the specific key in the customer
object.
If there is no property named enjoysCoffee
in the customer[enjoysCoffee]
object, it will return undefined
.
If your intention is to fetch the value of the enjoysCoffee
property from the customer
object, then the correct syntax should be customer["enjoysCoffee"]
;
function coffeeLoverExtended(customer) {
return customer["enjoysCoffee"];
}
var customer001 = {
name: "John Riley",
ticketNumber: "A01",
enjoysCoffee: true,
};
console.log(coffeeLoverExtended(customer001)); //true
To access a property of an object, you have to use either dot notation (.) or bracket notation ([]). Both customer["enjoysCoffee"]
and customer.enjoysCoffee
would yield the same result.
Here's an example with nested objects:
function coffeeLoverExtended(customer) {
// return customer.enjoysCoffeeObj["enjoysCoffee"];
// or
// return customer["enjoysCoffeeObj"].enjoysCoffee;
// or
// return customer["enjoysCoffeeObj"]["enjoysCoffee"];
// or
return customer.enjoysCoffeeObj.enjoysCoffee;
}
var customer001 = {
name: "John Riley",
ticketNumber: "A01",
enjoysCoffeeObj: {
enjoysCoffee: true,
},
};
console.log(coffeeLoverExtended(customer001)); //true
All the above return statements will output true
.