Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDaniel Benisti
Front End Web Development Techdegree Graduate 22,224 Pointswhy using []
on minut 7:24 why he uses [user.name] ? i mean why the [] instead of plain user.name
2 Answers
Steven Parker
231,248 PointsThe entire expression is "usersObject[user.name]
", so bracket notation is being used to access a specific property of the "usersObject". The value in user.name
is the name of the property being created.
Jesus Mendoza
23,289 PointsWhen using variables to access elements inside an object you have to use []
.
For example:
// Using plain property names
const obj = {
name: 'Jesús'
}
console.log(obj.name) // logs Jesús
// Using variables
const propertyName = 'name';
const obj2 = {
name: 'Jesús'
};
console.log(obj[propertyName]); // logs Jesús
Daniel Benisti
Front End Web Development Techdegree Graduate 22,224 PointsDaniel Benisti
Front End Web Development Techdegree Graduate 22,224 Pointsbut if i want to acces property in object with bracket notation i need to add a string with it , am i right? like this const peoples ={ name: dani, age: 22 } peoples["name"]
Steven Parker
231,248 PointsSteven Parker
231,248 PointsThat's right, but the string can be a literal (as in your example) or it can come from a variable (as what
user.name
holds).