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 trial

JavaScript JavaScript Array Iteration Methods Combining Array Methods Working with Objects in Arrays

why using []

on minut 7:24 why he uses [user.name] ? i mean why the [] instead of plain user.name

2 Answers

Steven Parker
Steven Parker
231,236 Points

The 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.

but 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
Steven Parker
231,236 Points

That'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).

Jesus Mendoza
Jesus Mendoza
23,289 Points

When 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