0

Say I have an array of objects like this:

function obj (name) {
    this.name = name
}
let x = {
    'foo': new obj('foo');
    'bar': new obj('bar');
}

Is there an advantage to using x['foo'].name over x['foo']['name]?

I recognize that [] notation is a lot more versatile when it comes to adding things to an object or when looping through an object with for so is there any reason besides ease of use that one would choose to access it with .? Does it provide a speed increase or is it just for readability?

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
Ryan Schaefer
  • 3,047
  • 1
  • 26
  • 46
  • 2
    `.propertyName` is not quite the same a `[propertyName]` ... it's actually the same as `['propertyName']` – Jaromanda X Mar 08 '18 at 00:18
  • That’s effectively what I meant – Ryan Schaefer Mar 08 '18 at 00:19
  • `[] notation is a lot more versatile when it comes to adding things to an object` - not really ... `[]` is useful if the property name contains spaces, or symbols like -, * + etc – Jaromanda X Mar 08 '18 at 00:19
  • If anything, dot notation is faster. – Bergi Mar 08 '18 at 00:19
  • 1
    .propertyName is easier to read, it's the standard way of doing so. But if you are iterating through the properties of an object, you have to use the other method. – Havenard Mar 08 '18 at 00:19
  • 1
    Sorry, I was addressing the title of the question, which is clearly not representative of the question – Jaromanda X Mar 08 '18 at 00:20
  • In normal JavaScript it’s equivalent. It’s important only in terms of readability/style. But in typed variants of JavaScript, like TypeScript and Closure, the brackets are often treated as a dynamic expression while the dotted form is treated like a static property. – Jeremy Mar 08 '18 at 00:21

1 Answers1

3

x.y is generally preferred as it is faster to write / nicer to use.

x["y"] is useful with obscure keys such as "d-2", "1.2" or other non-ascii characters.

In the first case, you can't do x.d-2 as this becomes x.d - 2 (completely different).

Tobiq
  • 2,489
  • 19
  • 38
  • The brackets notation also allows for dynamic access to properties. Trivial example: you have `properties = ["name", "age", "id"]` and then you do `properties.forEach( property => console.log(obj[property]) )` – VLAZ Mar 08 '18 at 00:29