Language: EN

javascript-notacion-punto-y-corchetes

Dot Notation or Bracket Notation in JavaScript

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

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

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 the properties of an object. It uses the object name followed by a dot and then the property name.

object.property
  • object: The object that contains the property.
  • property: The name of the property you want to access.

For example,

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

To access the name property:

student.name; // "Luis"

Bracket Notation

Bracket notation allows you to access the properties of an object using a string inside brackets.

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

This way is somewhat less convenient, but it is useful in certain cases. For example, when the property name contains invalid characters for dot notation.

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

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

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 it.

Let’s see 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 

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

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]];

It’s actually the same case as the previous one.