DEV Community

Cover image for Dot Notation vs Bracket Notation for Object Properties – What's the Difference?
Fahad Bin Faiz
Fahad Bin Faiz

Posted on

Dot Notation vs Bracket Notation for Object Properties – What's the Difference?

Dot Notation

Dot notation is simpler and more readable. It's used when:

  1. The property name is a valid identifier (contains only letters, digits, $, or _, and doesn’t start with a digit).
  2. You know the property name ahead of time.

For example:

const person = { name: 'alice', age: 30 };
console.log(person.name); // 'alice'
Enter fullscreen mode Exit fullscreen mode

Bracket Notation

Bracket notation is more flexible and allows you to:

  1. Use property names stored in variables.
  2. Access properties with special characters, spaces, or numbers that aren’t valid identifiers.
  3. Dynamically build property names at runtime.

Examples:
1. Using variables to access properties:

const person = { name: 'alice', age: 30 };
const prop = 'name';
console.log(person[prop]); // 'alice'

Enter fullscreen mode Exit fullscreen mode

2.Properties with special characters or spaces:

const person = { 'first name': 'alice', age: 30 };
console.log(person['first name']); // 'alice'

Enter fullscreen mode Exit fullscreen mode

3.Dynamically generated property names:

const property = 'name';
console.log(person[property]); // 'alice'

Enter fullscreen mode Exit fullscreen mode

When to Use Bracket Notation

  • If the property name is dynamic or stored in a variable.
  • If the property name has spaces, special characters, or starts with a number.

For most other cases, dot notation is preferred because it’s more readable and concise.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay