Home > Web Front-end > JS Tutorial > Dot Notation vs Bracket Notation for Object Properties – What&#s the Difference?

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

Barbara Streisand
Release: 2024-11-15 01:52:02
Original
658 people have browsed it

Dot Notation vs Bracket Notation for Object Properties – What

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'
Copy after login

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'

Copy after login

2.Properties with special characters or spaces:

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

Copy after login

3.Dynamically generated property names:

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

Copy after login

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.

The above is the detailed content of Dot Notation vs Bracket Notation for Object Properties – What&#s the Difference?. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template