javascript-notacion-punto-y-corchetes

Dot Notation or Bracket Notation in JavaScript

  • 3 min

Two of the most common ways to access an object’s properties are dot notation and bracket notation.

Each method has its advantages and disadvantages, so let’s see when to use each one 👇

FeatureDot NotationBracket Notation
Access to propertiesYesYes
Use of variablesNoYes
Property namesLimitedAny
ReadabilityMore readableLess readable

Dot Notation

Dot notation is the most common way to access an object’s properties. You use the object’s name followed by a dot and then the property name.

object.property
Copied!
  • object: The object containing the property.
  • property: The name of the property you want to access.

For example,

const student = {
  name: "Luis",
  age: 30
};
Copied!

To access the name property:

student.name; // "Luis"
Copied!

Bracket Notation

Bracket notation allows you to access an object’s properties using a string inside brackets.

object[property]
Copied!
  • object: The object containing the property.
  • “property”: The property name in quotes, or an expression that evaluates to a string.

This form is a bit less convenient, but it’s useful in certain cases. For example, when the property name contains characters that are invalid for dot notation.

Let’s see it with an example as well. To access the name property using bracket notation we would do:

student["name"]; // "Luis"
Copied!

When to Use Bracket Notation

In general, we will primarily use dot notation. We will use brackets when we have a case where we cannot use dot notation.

Let’s look at them.

Properties with Special Characters

Bracket notation is necessary if the property name contains special characters or spaces.

const person = {
"full name": "Ana Pérez"
};

person["full name"]; // "Ana Pérez"

person.full name;   // ❌ I can't do that because of the space 
Copied!

Dynamic Properties

When the property name is determined at runtime.

const property = "age";

person[property]; // 21

person.¿?¿?¿? // ❌ We wouldn't know what to put there
Copied!

Computed Properties You can use expressions inside the brackets to access properties that are generated dynamically.

const index = 2; // imagine the user selects this
const properties = ["name", "age", "profession"];

person[properties[index]];
Copied!

This is actually the same case as the previous one.