Field accessors and method chaining

Object methods and fields are accessed using dot notation, a common construct of many object-oriented languages.

Field access

The dot prefix (.) is used to access an object member or property, as shown in the .aKey notation in this example:

let object = {
  aKey: "one",
  bKey: "two"
}
object.aKey
"one"

Method calls

Methods can be chained using dot notation to compose complex queries where the output of the previous method is the input of the next method.

In this example, the query returns up to ten documents from all the documents in the Books collection:

Product.all().take(10)

Anonymous field and method access

A variant of dot notation, the optional chaining operator can be used to access a field or invoking a method, returning null instead of an error if the left side of the expression evaluates to null.

Access an anonymous field example:

let book = {
  name: 'Hamlet',
  author: {
    name: 'Shakespeare'
  }
}

book.writer?.name

The example returns null instead of an error provided type checking is disabled.

Invoke an anonymous method example:

let book = {
  name: 'Hamlet',
  author: {
    name: 'Shakespeare'
  }
}

book.author.customMethod?.()

The example returns null instead of an error provided type checking is disabled.

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!