0

I have two codes that are working fine but I don't understand why in one of them I need to use brackets and in the other one, I don't. Codes are taken from FreeCodeCamp tutorials.

First code:

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {

  var numbUsers = 0;
  for (let user in obj){
    if (obj[user].online){   
        numbUsers++;       
    }                        
  }  
  return numbUsers;  
}
console.log(countOnline(users));

There, we need to use brackets on [user], if you use dot it won’t work. What I understood, is that user is not a variable (variables are the ones that can be accessed by dots), since it’s an object we need the brackets.

Second code:

let user = {
  name: 'Kenneth',
  age: 28,
  data: {
    username: 'kennethCodesAllDay',
    joinDate: 'March 26, 2016',
    organization: 'freeCodeCamp',
    friends: [
      'Sam',
      'Kira',
      'Tomo'
    ],
    location: {
      city: 'San Francisco',
      state: 'CA',
      country: 'USA'
    }
  }
};

function addFriend(userObj, friend) {

  userObj.data.friends.push(friend);

  return userObj.data.friends;

}

console.log(addFriend(user, 'Pete'));

In this code, as I can see, there is an object inside an object , and it’s being accessed only with dots and it works perfectly… Why is that? Why I wasn't able to do this in the first code?

I need to understand how this works, otherwise I won't be able to write code on Javascript properly.

Thank you in advance to everyone who is wiling to help on this Friday night hehe.

:D

Ana
  • 70
  • 1
  • 9
  • No, that question doesn't answer mine... – Ana Jul 20 '19 at 02:41
  • Whenever you want to use `variable` to access key or key is not a valid JS identifier you must to use `[]` else you can use any of them – Code Maniac Jul 20 '19 at 02:42
  • There are lots of answer which addresses this when to use which, do read them once if you still fill your question isn't answered there let me know – Code Maniac Jul 20 '19 at 02:45
  • Mmmm thank you for the explanation but I still don't understand... Now that was marked as duplicated no one willl be able to see the post? – Ana Jul 20 '19 at 02:46
  • Well in the first snippet you're checking for each of the key and adding the counts so you need to loop over object, and which is done by `for ... in` and you need `[]` as you're accessing value using `variable`, whereas in your second snippet you're directly accessing property called `friends` and pushing values to it, so you don't need to use `[]` – Code Maniac Jul 20 '19 at 02:51
  • Now I understand hehe. Thank you very much! do you want me to delete the thread since its a duplicate? :D or u can delete it yourself if u can . Thank u again! – Ana Jul 20 '19 at 19:54

0 Answers0