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