Accessing an object's properties

In the “Basic Data Structures: Iterate Through the Keys of an Object with a for…in Statement” (third to last) exercise we can only access an object property with usersObj[user].online and not with usersObj.user.online.

Why is that?

FULL CODE:

function countOnline(usersObj) {
// FCC Solution
    let result = 0;
  for (let user in usersObj) {
    if (usersObj[user].online === true) {
      result++;
    }
  }
  return result;
// My solution (didn't work because of the way I was attempting to access the object property)
  let number = 0;
  for (let user in usersObj) {
    if (usersObj.user.online === true) {
      number++;
    }
  }
  return number;
}

That’s because the property represented by the user variable in the userObj might not be a valid javascript identifier.
The following is from an article:

The dot property accessor works correctly when the property name is a valid identifier. An identifier in JavaScript contains Unicode letters, $ , _ , and digits 0..9 , but cannot start with a digit.

const weirdObject = {
  'prop-3': 'three',
  '3': 'three'
};

weirdObject.prop-3; //will thrown a NaN error
weirdObject.3 // will throw a syntax error (unexpected number)

The dot notation doesn’t work in this case since they are invalid identifiers.

You want to use bracket notation:

weirdObject[‘prop-3’]; // => ‘three’
weirdObject[3]; // => ‘three’

That’s why your solution didn’t work.

Here’s the link to the full article: https://dmitripavlutin.com/access-object-properties-javascript/

1 Like