Accessing properties in JavaScript: dot notation or brackets?

Let's say we have an object called rectangulo and a property called area. We can access this property in the following ways:

  • dot notation: rectangulo.area.
  • bracket notation: rectangulo['area'].

I understand the advantage of using bracket notation for cases where properties:

  • have characters such as spaces, hyphens, etc.
  • are not known until runtime.

Other than these reasons intuitive, are there others to use one notation for the other? If so, which ones?

2 answers

There are two main (others too, which do not fall within the scope of this answer) ways to access properties in an object. See more in "property accessors" in the documentation.

The first of these is the dot notation – for example object.property. In this case, because the Access is " hard-coded " in the code, you cannot use it when you need dynamic access.

The benefit of this mode is greater readability. You can use the notation any property that is a valid identifier in JavaScript. In this way, you can access a property using the dot notation as long as it is composed of Unicode letters, $, _ and do not start by numbers.

Then:

const myObj = {
  1: 'One',
  2: 'Two',
  Π: Math.PI, // "PI" é uma letra válida no Unicode
  name: 'Bob',
  $: 'jQuery?'
};

// myObj.1; --> Inválido porque 1 não é identificador válido
// myObj.2; --> Inválido porque 2 não é identificador válido

console.log(myObj.Π); // 3.141592653589793
console.log(myObj.name); // Bob
console.log(myObj.$); // jQuery?

The other main access method uses the bracket notation [ and ], whose syntax is object[property]. This notation is commonly used when it is necessary to access the property dynamically or when the property name is not a valid identifier.

As seen above, this property should also be used to access properties that are not valid identifiers in JavaScript.

Are also used to access properties whose key is a number (number) or symbol (symbol).

Then:

const SYMBOL_KEY = Symbol('name');

const obj = {
  1: 'One',
  [SYMBOL_KEY]: 'Bob',
  age: 10,
  'not-a-valid-identifier': 'Value'
};

console.log(obj[1]); // One
console.log(obj[SYMBOL_KEY]); // Bob
console.log(obj['age']); // 10
console.log(obj['not-a-valid-identifier']); // Value

In the ECMAScript 2020 edition, JavaScript allows use optional Access to object properties. It works with both bracket notation and dot notation. It is useful for nested accesses.

 5
Author: Luiz Felipe, 2021-01-27 18:49:32

It is always difficult to prove a negative (in this case that there is no other benefit to using one notation or another).

From what you quoted seems to be all the differences between the two notations.

I usually use dot notation whenever I can, since it's easier to read, and bracket notation in case I need to determine the object property dynamically as my_obj[my_var].

 0
Author: renatomt, 2020-07-22 13:41:53