Accessing Object Properties in JS: Full Tutorial

Learn every way to access JavaScript object properties including dot notation, bracket notation, optional chaining, destructuring, and dynamic property access with practical code examples.

JavaScriptbeginner
13 min read

Once you have created an object in JavaScript, you need to read its values. JavaScript provides multiple ways to access object properties, and each method has specific use cases where it works best. Dot notation is the most common, but bracket notation handles dynamic keys, optional chaining prevents runtime errors on nested data, and destructuring extracts multiple values at once.

This tutorial covers every property access pattern you will encounter in JavaScript development, from basic syntax to advanced dynamic access techniques.

Dot Notation

Dot notation is the simplest and most readable way to access object properties. Use the object name, a dot, and the property name:

javascriptjavascript
const user = {
  firstName: "Alice",
  lastName: "Johnson",
  age: 28,
  email: "alice@example.com"
};
 
console.log(user.firstName); // "Alice"
console.log(user.age);       // 28
console.log(user.email);     // "alice@example.com"

Chaining Dot Notation for Nested Objects

Dot notation chains naturally for accessing properties inside nested objects:

javascriptjavascript
const company = {
  name: "TechCorp",
  address: {
    street: "123 Main St",
    city: "San Francisco",
    state: "CA",
    zip: "94102"
  },
  ceo: {
    name: "Alice Johnson",
    contact: {
      email: "alice@techcorp.com",
      phone: "555-0100"
    }
  }
};
 
console.log(company.address.city);         // "San Francisco"
console.log(company.ceo.contact.email);    // "alice@techcorp.com"

Dot Notation Limitations

Dot notation only works with valid JavaScript identifiers. It cannot handle property names that contain spaces, start with numbers, or use special characters:

javascriptjavascript
const data = {
  "first-name": "Alice",    // Hyphen in name
  "2nd place": "Bob",       // Starts with number
  "has spaces": true,       // Contains spaces
  normalKey: "works fine"
};
 
// console.log(data.first-name);  // SyntaxError!
// console.log(data.2nd place);   // SyntaxError!
console.log(data.normalKey);      // "works fine"

Bracket Notation

Bracket notation uses square brackets with a string (or expression) to access properties. It handles any property name, including those that break dot notation:

javascriptjavascript
const data = {
  "first-name": "Alice",
  "2nd place": "Bob",
  "has spaces": true,
  normalKey: "works fine"
};
 
console.log(data["first-name"]); // "Alice"
console.log(data["2nd place"]);  // "Bob"
console.log(data["has spaces"]); // true
console.log(data["normalKey"]);  // "works fine"

Dynamic Property Access

The real power of bracket notation is using variables and expressions to determine which property to access at runtime:

javascriptjavascript
const user = {
  firstName: "Alice",
  lastName: "Johnson",
  age: 28,
  role: "admin"
};
 
const field = "firstName";
console.log(user[field]); // "Alice"
 
// Useful in functions that work with any property
function getProperty(obj, key) {
  return obj[key];
}
 
console.log(getProperty(user, "role")); // "admin"
console.log(getProperty(user, "age"));  // 28

Iterating Over Properties Dynamically

Bracket notation is essential when you need to access properties inside loops:

javascriptjavascript
const scores = {
  math: 92,
  science: 88,
  english: 95,
  history: 78
};
 
// Calculate average using dynamic access
const subjects = Object.keys(scores);
let total = 0;
 
for (const subject of subjects) {
  total += scores[subject]; // Bracket notation with variable
}
 
const average = total / subjects.length;
console.log(`Average score: ${average}`); // "Average score: 88.25"

Dot Notation vs Bracket Notation

FeatureDot NotationBracket Notation
Syntaxobj.keyobj["key"] or obj[variable]
ReadabilityMore readableSlightly more verbose
Dynamic keysNot supportedFully supported
Special charactersNot supportedFully supported
Computed expressionsNot supportedSupported (obj["a" + "b"])
PerformanceMarginally fasterMarginally slower
Use caseKnown, valid property namesDynamic or special property names

Rule of thumb: Use dot notation as your default. Switch to bracket notation only when the property name is dynamic, contains special characters, or comes from a variable.

Optional Chaining (?.)

Optional chaining (?.) safely accesses nested properties without throwing an error if an intermediate value is null or undefined. Instead of crashing, it returns undefined:

javascriptjavascript
const user = {
  name: "Alice",
  address: {
    city: "San Francisco"
  }
};
 
// Without optional chaining (dangerous)
// console.log(user.profile.avatar); // TypeError: Cannot read properties of undefined
 
// With optional chaining (safe)
console.log(user.profile?.avatar);       // undefined (no error)
console.log(user.address?.city);         // "San Francisco"
console.log(user.address?.zipCode);      // undefined

Chaining Multiple Levels

Optional chaining works at every level of a deep property chain:

javascriptjavascript
const apiResponse = {
  data: {
    users: [
      {
        name: "Alice",
        settings: {
          theme: "dark"
        }
      }
    ]
  }
};
 
// Safe deep access
const theme = apiResponse?.data?.users?.[0]?.settings?.theme;
console.log(theme); // "dark"
 
// Missing data returns undefined instead of crashing
const missing = apiResponse?.data?.posts?.[0]?.title;
console.log(missing); // undefined

Optional Chaining with Methods

You can also use optional chaining to call methods that might not exist:

javascriptjavascript
const calculator = {
  add(a, b) { return a + b; }
};
 
console.log(calculator.add?.(2, 3));       // 5
console.log(calculator.subtract?.(5, 2));  // undefined (method doesn't exist)

Destructuring Assignment

Destructuring lets you extract multiple properties into individual variables in a single statement:

javascriptjavascript
const product = {
  name: "Laptop",
  price: 999.99,
  brand: "TechBrand",
  inStock: true
};
 
// Extract specific properties
const { name, price, inStock } = product;
 
console.log(name);    // "Laptop"
console.log(price);   // 999.99
console.log(inStock); // true

Destructuring with Renaming

You can rename variables during destructuring to avoid naming conflicts:

javascriptjavascript
const user = {
  name: "Alice",
  age: 28
};
 
const product = {
  name: "Laptop",
  price: 999
};
 
// Rename to avoid conflict
const { name: userName } = user;
const { name: productName } = product;
 
console.log(userName);    // "Alice"
console.log(productName); // "Laptop"

Default Values in Destructuring

Provide fallback values for properties that might not exist:

javascriptjavascript
const config = {
  theme: "dark",
  language: "en"
};
 
const {
  theme,
  language,
  fontSize = 16,        // Default: property doesn't exist
  notifications = true  // Default: property doesn't exist
} = config;
 
console.log(theme);         // "dark"
console.log(fontSize);      // 16 (default applied)
console.log(notifications); // true (default applied)

Nested Destructuring

Extract properties from nested objects in one declaration:

javascriptjavascript
const order = {
  id: "ORD-001",
  customer: {
    name: "Alice",
    email: "alice@example.com"
  },
  items: [
    { product: "Laptop", qty: 1 }
  ],
  shipping: {
    address: {
      city: "San Francisco",
      state: "CA"
    }
  }
};
 
const {
  id,
  customer: { name: customerName, email },
  shipping: { address: { city } }
} = order;
 
console.log(id);           // "ORD-001"
console.log(customerName); // "Alice"
console.log(city);         // "San Francisco"

Accessing Properties in Function Parameters

Destructuring in function parameters cleans up code that receives objects:

javascriptjavascript
// Without destructuring
function displayUser(user) {
  console.log(`${user.name} (${user.age}) - ${user.email}`);
}
 
// With destructuring
function displayUserClean({ name, age, email }) {
  console.log(`${name} (${age}) - ${email}`);
}
 
// With defaults
function createButton({ text = "Click", color = "blue", size = "medium" } = {}) {
  return `<button class="${color} ${size}">${text}</button>`;
}
 
console.log(createButton({ text: "Submit", color: "green" }));
// '<button class="green medium">Submit</button>'
 
console.log(createButton());
// '<button class="blue medium">Click</button>'

Checking If a Property Exists

The in Operator

The in operator checks whether a property exists on an object or its prototype chain:

javascriptjavascript
const user = {
  name: "Alice",
  age: 28,
  email: undefined  // Property exists but is undefined
};
 
console.log("name" in user);     // true
console.log("email" in user);    // true (exists, even though undefined)
console.log("phone" in user);    // false
console.log("toString" in user); // true (inherited from Object.prototype)

hasOwnProperty()

hasOwnProperty() checks only the object's own properties, not inherited ones:

javascriptjavascript
const user = { name: "Alice", age: 28 };
 
console.log(user.hasOwnProperty("name"));     // true
console.log(user.hasOwnProperty("toString")); // false (inherited)
 
// Modern alternative: Object.hasOwn() (ES2022)
console.log(Object.hasOwn(user, "name"));     // true
console.log(Object.hasOwn(user, "toString")); // false

Property Existence Comparison

MethodChecks OwnChecks PrototypeHandles undefined Values
"key" in objYesYesYes (returns true)
obj.hasOwnProperty("key")YesNoYes (returns true)
Object.hasOwn(obj, "key")YesNoYes (returns true)
obj.key !== undefinedYesYesNo (false for undefined values)
obj.key != nullYesYesNo (false for null and undefined)

Common Mistakes to Avoid

Accessing Properties on null/undefined

javascriptjavascript
let user = null;
 
// WRONG: crashes
// console.log(user.name); // TypeError
 
// CORRECT: guard with optional chaining
console.log(user?.name); // undefined
 
// CORRECT: guard with conditional
if (user) {
  console.log(user.name);
}

Confusing Property Access with Variable Access

javascriptjavascript
const obj = { name: "Alice" };
const name = "name";
 
// These are NOT the same:
console.log(obj.name);  // "Alice" (accesses the 'name' property)
console.log(obj[name]); // "Alice" (uses variable 'name' which equals "name")
 
const field = "age";
// console.log(obj.field); // undefined (there's no property called "field")
console.log(obj[field]);   // undefined (there's no property called "age")
Rune AI

Rune AI

Key Insights

  • Dot notation: Default choice for known, valid property names with the cleanest syntax
  • Bracket notation: Required for dynamic keys, special characters, and computed property names
  • Optional chaining: Prevents TypeError crashes when accessing nested properties on potentially null or undefined values
  • Destructuring: Extracts multiple properties into variables in one statement, with support for renaming and defaults
  • Property existence checks: Use Object.hasOwn() for own-property checks and in operator for prototype-inclusive checks
RunePowered by Rune AI

Frequently Asked Questions

When should I use bracket notation over dot notation?

Use bracket notation when the property name is stored in a variable, when it contains special characters (hyphens, spaces), when it starts with a number, or when you need to compute the property name with an expression. In all other cases, prefer dot notation for better readability.

Does optional chaining work with bracket notation?

Yes. You can combine optional chaining with bracket notation using `?.[]` syntax. For example, `user?.["first-name"]` safely accesses a hyphenated property name. You can also use `?.()` for optional method calls, like `obj.method?.()`.

Is destructuring slower than dot notation?

The performance difference is negligible for typical usage. JavaScript engines optimize destructuring efficiently, and the readability benefit of extracting multiple properties at once usually outweighs any microscopic performance difference. Use whichever approach makes your code clearer.

What happens when I access a property that does not exist?

ccessing a nonexistent property returns `undefined` rather than throwing an error. This is different from accessing a property on `null` or `undefined` itself, which throws a `TypeError`. Use optional chaining (`?.`) to guard against both cases.

Can I destructure and keep the original object too?

Yes. Destructuring creates new variables but does not modify the original object. You can destructure specific properties and still reference the full object by its original name. You can also use rest syntax (`...rest`) to capture remaining properties into a new object.

Conclusion

JavaScript offers multiple ways to access object properties, and choosing the right one depends on your specific situation. Dot notation covers most day-to-day property access with clean syntax, bracket notation handles dynamic and special-character keys, optional chaining makes nested access safe, and destructuring extracts multiple values efficiently. Combining these techniques lets you write code that is both readable and resilient to missing data.