Blocks and lexical scoping

Blocks

A block is an expression that encapsulates one or more statements or expressions, and is enclosed by { }:

{
    let a = 1
    let b = 2
    a + b
}
3

The last statement in a block must be an expression.

A block is itself an expression, and has the type and result of the last expression of the block:

let x = {
    let a = 1
    let b = 2
    a + b
}
x
3

Scope

A block defines variable scope. Variables declared in a block are scoped to the block and can’t be referenced outside of the block.

let x = "foo"
let y = {
  let x = "bar"
  x
}
[x, y]
[
  "foo",
  "bar"
]

In the example, two x variables are declared. One with local scope and one with global scope. Variable y has global scope and is the value of the block.

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!