Sobes.tech
Intern

How do you get an object's property in JavaScript?

sobes.tech AI

Answer from AI

There are two main ways:

  1. Dot access (.): Used when the property name is known in advance and is a valid JavaScript identifier.

    const obj = { name: 'Alice' };
    const name = obj.name; // 'Alice'
    
  2. Bracket access ([]): Used when the property name is stored in a variable, contains special characters (spaces, hyphens, etc.), or is a number.

    const obj = { 'user-name': 'Bob', 123: 'number property' };
    const propertyName = 'user-name';
    const userName = obj[propertyName]; // 'Bob'
    const numberProperty = obj[123]; // 'number property'
    

Additionally:

  • Object destructuring: Allows extracting properties from an object into separate variables.

    const obj = { firstName: 'Charlie', lastName: 'Brown' };
    const { firstName, lastName } = obj;
    // firstName = 'Charlie'
    // lastName = 'Brown'
    
  • Optional chaining operator (?.): Safely accesses nested properties, preventing errors if intermediate properties are missing.

    const obj = { user: { profile: { age: 30 } } };
    const age = obj.user?.profile?.age; // 30
    
    const anotherObj = { user: {} };
    const city = anotherObj.user?.profile?.city; // undefined (no error)