hasOwnProperty - Keys to Strings?

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.

Challenge: Check if an Object has a Property

Link to the challenge:

Because if you just put the property without string it will try to find a variable or a function with that name ex:

obj.hasOwnProperty(Alan);

It will try to look for a variable Alan not the specific text Alan.

1 Like

Object property names are strings (or Symbol) even if you do not explicitly write them as such (type coercion will happen).

Property names

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.

3 Likes

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.

The Basic JavaScript: Build JavaScript Objects challenge does touch on it briefly.

Code example

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.