Tell us what’s happening:
I understand everything about this except for why I need to write each key as a string when using hasOwnProperty(). The keys I’m searching for don’t appear to be strings in the object users. Would someone please explain this to me?
Thanks.
Your code so far
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
function isEveryoneHere(obj) {
// Only change code below this line
if (
obj.hasOwnProperty("Alan") &&
obj.hasOwnProperty("Jeff") &&
obj.hasOwnProperty("Sarah") &&
obj.hasOwnProperty("Ryan")
) {
return true;
}
return false;
// Only change code above this line
}
console.log(isEveryoneHere(users));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.
Property names are string or Symbol. Any other value, including a number, is coerced to a string. This outputs ‘value’, since 1 is coerced into ‘1’.
let object = {}
object['1'] = 'value'
console.log(object[1])
As said, if you didn’t write obj.hasOwnProperty("Alan"), but obj.hasOwnProperty(Alan), then Alan would be an identifier (variable name) and no such identifier exsistes in the scope of the isEveryoneHere function.
Thanks, that helps. I just don’t recall ever seeing an explanation that property names are considered strings. They definitely look more like variables to me.
In this example, all the properties are stored as strings, such as - “name”, “legs”, and “tails”. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
Code example
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.