# Functions

```go
func add(a, b number) number {
    return a + b
}

func greet(name string) {          // without a result type it returns nothing
    console.log(`Hello, ${name}`)
}
```

```js
function add(a, b) {
  return a + b
}

function greet(name) {
  console.log(`Hello, ${name}`)
}
```

Adjacent parameters of the same type can be grouped: `a, b number` is the same as
`a number, b number`.

An object type is a result when the body follows it, `func origin() { x, y number } { ... }`; in
parentheses, `({ x, y number })`, it is one anywhere.

### Default values and the rest of the arguments

```go
func greet(name string = "you", times = 1) string {
    return name.repeat(times)
}

func log(level string, ...parts any[]) {
    console.log(level, ...parts)
}

greet()                    // "you"
log("info", "saved", 3)
```

- Parameters with default values come last and may be left out in a call. A default value without
  a type gives the parameter its type, `times = 1`, and sees the parameters before it.
- `...parts any[]` takes the arguments after the others in an array; it is the last parameter, and
  each argument is checked against the type of the elements.
- Both are written the same way in functions, methods, constructors, `func` literals and arrow
  functions, and stay the same in JS.

### Multiple results

```go
func divmod(a, b number) (number, number) {
    return Math.floor(a / b), a % b
}

const q, r = divmod(17, 5)
const _, rest = divmod(17, 5)      // _ skips a value
```

```js
function divmod(a, b) {
  return [Math.floor(a / b), a % b]
}

const [q, r] = divmod(17, 5)
const [, rest] = divmod(17, 5)
```

The rules are those of Go:

- several values can only be returned with `return` and unpacked at once into variables in
  `let`/`const` or in an assignment;
- the number of variables must match the number of values;
- `divmod(17, 5) + 1` is a compile error.

### Anonymous functions

```go
const square = func(x number) number { return x * x }
const sum = (a, b number) => a + b
const doubled = nums.map(x => x * 2)      // the type of x comes from the context
```

Arrow functions are as in JS, with Go-style types. If the type of a parameter cannot be inferred
from the context, it must be written.

A `func` literal compiles to an arrow function too, so `this` inside it is the `this` of the
surrounding method, not a new one as with `function` in JS.

### defer

`defer` postpones a call until the function exits: on `return`, at the end of the body or on an
exception.

```go
func readConfig(path string) (string, error) {
    const fd = fs.openSync(path, "r")
    defer fs.closeSync(fd)

    const text = fs.readFileSync(fd, "utf8")
    if text == "" {
        return "", error("empty config")
    }
    return text, null
}
```

```js
function readConfig(path) {
  const fd = fs.openSync(path, 'r')
  try {
    const text = fs.readFileSync(fd, 'utf8')
    if (text === '') {
      return ['', new Error('empty config')]
    }
    return [text, null]
  } finally {
    fs.closeSync(fd)
  }
}
```

The rules are those of Go:

- the function and its arguments are evaluated at the `defer`, and the call happens on exit;
- several deferred calls run in reverse order;
- if a deferred call throws, the others still run;
- `defer` belongs to the whole function, not to a block: a `defer` in a loop adds a call on every
  iteration, and all of them run when the function exits;
- `defer` is allowed only inside functions and methods;
- inside `defer { ... }` there can be no `return`, and `break` and `continue` only in loops nested
  in it: deferred code cannot change how the function ended.

```go
func countdown() {
    for let i = 0; i < 3; i++ {
        defer console.log(i)
    }
}
// countdown() prints 2, 1, 0
```

For several actions there is a block form; its content runs as a whole on exit:

```go
defer {
    conn.close()
    console.log("connection closed")
}
```

If all the `defer`s are at the top level of the function's body, the compiler writes nested
`try/finally`, as in the example above. If a `defer` is inside an `if` or a loop, the deferred calls
are collected in a stack and run in `finally`.

