# Conditions and loops

### if

```go
if x > 0 {
    console.log("positive")
} else if x < 0 {
    console.log("negative")
} else {
    console.log("zero")
}
```

No parentheses around the condition, braces are required. The condition must be a `bool`: unlike
JS, there is no truthy/falsy. `if count {` is an error, write `if count > 0 {`, and instead of
`if user {` write `if user != null {`.

An object literal in the header of `if`, `for` or `switch` goes in parentheses, or its `{` would be
taken for the start of the block (the same rule as in Go).

> **Experimental:** the initializer of `if` and `switch`; the rest of `if` is stable.

**An initializer** goes before the condition, as in Go: a `const` or `let` declaration and `;`. Its
variables are seen in the condition and in every branch, `else` included, and not after the `if`,
so a value that only the `if` needs does not stay in the function:

```go
if const user, err = load(id); err != null {
    console.log(err.message)
} else if let age = user.age; age >= 18 {
    console.log(`${user.name}, ${age}`)
}
```

```js
{
  const [user, err] = load(id)
  if (err != null) {
    console.log(err.message)
  } else {
    let age = user.age
    if (age >= 18) {
      console.log(`${user.name}, ${age}`)
    }
  }
}
```

The condition narrows the variables, as any condition does: in `if const u = find(); u != null`,
`u` is not null in the branch. `switch` takes an initializer in the same way (see `switch`); the
`{if}` of markup does not: declare the value before the markup.

### for, the only loop

| Rook                               | JS                                                              |
| ---------------------------------- | --------------------------------------------------------------- |
| `for let i = 0; i < n; i++ { }`    | `for (let i = 0; i < n; i++) { }`                               |
| `for i in 0..n { }`                | `for (let i = 0, $$end = n; i < $$end; i++) { }`                |
| `for x in items { }`               | `for (const x of items) { }`                                    |
| `for i, x in items { }` (an array) | `for (let i = 0; i < items.length; i++) { const x = items[i] }` |
| `for k, v in scores { }` (a Map)   | `for (const [k, v] of scores.entries()) { }`                    |
| `for v in scores { }` (a Map)      | `for (const v of scores.values()) { }`                          |
| `for v in seq { }` (an iterator)   | `for (const v of seq()) { }`                                    |
| `for line in lines { }` (async)    | `for await (const line of lines) { }`                           |
| `for cond { }`                     | `while (cond) { }`                                              |
| `for { }`                          | `while (true) { }`                                              |

An array or a typed array with an index goes over its indexes, which is faster than over the pairs
of `entries()`: the array is read once, as `entries()` would read it, so a loop that assigns the
variable of the array goes on over the old one. Without the index, `for _, x in items`, it is
`for...of`.

**A range,** `for i in 0..n`, goes over the numbers from the first up to the second, without it:
`0..3` gives 0, 1 and 2, and `5..2` nothing. Both ends are numbers and are computed once, before the
loop, as in Go: a loop that changes `n` goes on to the old end. The variable is a number that the
body cannot assign, as any variable of `for ... in`. A range is written only after `in`, with one
variable (`for i, x in 0..n` is an error), and not with `go for`, which goes over an array. In
`{for}` of markup it is the array of the numbers, `$$numbers(0, n)`.

`for x in items` goes over the **values**, like `for...of` in JS or `for x in` in Python and Rust,
not over the keys like `for...in` in JS. In Go, `for i := range xs` with one variable gives the
index; here one variable gets the value, and two get the index and the value.

- **Besides arrays and strings,** `for` goes over what the lib files make iterable (with
  `[Symbol.iterator]()`): a `Set`, a typed array, a `NodeList`, an iterator. Two variables need
  positions or keys: a typed array and a `NodeList` give the index and the value, as an array does;
  a `Set` has no keys.
- **A string** gives its characters, as `for...of` does: a character is a code point, so `😀` is
  one. With two variables, `for i, c in s`, `i` is the number of the character, not its index in
  the UTF-16 string: the loop compiles to `Array.from(s).entries()`.
- **A Map** gives its keys and values, as a map in Go: `for name, score in scores`. One variable
  gets the values, as with an array, and compiles to `scores.values()`. A value whose type is not
  known (`any`) is tested at runtime, so that a Map gives its values there too; code built with
  `--no-check` loops with `for...of` as it is.
- **A typed array** is indexed as an array is: `data[i]` reads and writes a number, and it can go
  where an `ArrayLike<number>` is expected, as in `Array.from(data)`.
- **An async iterable,** whose values come from `[Symbol.asyncIterator]()` of its `.d.ts`, is gone
  over with `for await` of JS: a stream of Node (`for chunk in request`), the lines of `readline`
  (`for line in createInterface({ input })`), a `ReadableStream` with `@types/node`, the cursor of
  a database. Each value waits for its Promise, as the values of a channel do, so the loop is
  allowed only where `await` is; it has no keys. `break` and `return` close the iterator, as they
  do in JS. A type that is iterable at once too goes over at once.

`break` and `continue` work as usual; to leave a loop around the one they are in, give it a label
(see "Labels").

### Iterators

```go
func count(n number) func(yield func(number) bool) {
    return func(yield func(number) bool) {
        defer console.log("done")
        for let i = 0; i < n; i++ {
            if !yield(i) {
                return
            }
        }
    }
}

for i in count(10) {
    if i == 3 {
        break
    }
}
const firstThree = count(1_000_000)().take(3).toArray()
```

```js
function count(n) {
  return function* () {
    try {
      for (let i = 0; i < n; i++) {
        yield i
      }
    } finally {
      console.log('done')
    }
  }
}

for (const i of count(10)()) {
  if (i === 3) {
    break
  }
}
const firstThree = count(1_000_000)().take(3).toArray()
```

An iterator is a function whose one parameter is named `yield`, as in Go 1.23:
`func(yield func(T) bool)` gives values of `T`, and `func(yield func(K, V) bool)` gives pairs. It
calls `yield(v)` for each value; `for v in seq` goes over them and `for k, v in seq` over the pairs,
where one variable gets the second of a pair, as with a Map.

- **The name makes the type:** `func(yield func(T) bool)` is an iterator, and `func(func(T) bool)`
  a function that takes a callback; neither goes where the other is expected. A function type may
  name its parameters, as in Go.
- **It compiles to a JS generator** (`function*`): `yield(v)` becomes `yield v`, and
  `yield(k, v)` becomes `yield [k, v]`. `if !yield(v) { return }`, the way an iterator of Go stops,
  becomes `yield v`: when the loop stops, with `break`, `return` or an exception, JS closes the
  generator where it yields, so the iterator returns there and its `defer`s run. For the same
  reason a `yield(v)` used as a value is always `true`.
- **A lazy JS iterator:** `seq()`, a call without arguments, gives the generator, with the helpers
  of iterators: `seq().filter(f).take(5).toArray()`. JS code goes over it with
  `for (const v of seq())`, and declarations for TypeScript give it as `() => Generator<T>`.
  Calling an iterator with a function, as Go allows, is an error.
- **What a generator cannot do:** `yield` is called only in the body of the iterator itself, not
  in a function inside it (`items.forEach(x => yield(x))` is an error: loop with `for` there), and
  it is not passed on or kept. An iterator is written with `func`: a declaration, a literal or a
  method, not an arrow function. It is not async, and it returns nothing.
- `for` over an iterator whose type is not known (`any`) calls it at runtime.

### switch

```go
switch cmd {
case "start", "run":
    start()
case "stop":
    stop()
default:
    console.log("unknown command")
}
```

```js
switch (cmd) {
  case 'start':
  case 'run':
    start()
    break
  case 'stop':
    stop()
    break
  default:
    console.log('unknown command')
}
```

Every `case` ends with an implicit `break`; several values are separated by commas.

`switch` without an expression replaces a long chain of `if`s:

```go
switch {
case score >= 90:
    grade = "A"
case score >= 75:
    grade = "B"
default:
    grade = "C"
}
```

```js
if (score >= 90) {
  grade = 'A'
} else if (score >= 75) {
  grade = 'B'
} else {
  grade = 'C'
}
```

`switch` takes an initializer as `if` does, `switch const kind = node.kind; kind { ... }`, also
without an expression: `switch const n = items.length; { case n > 10: ... }`.

### Labels

> **Experimental:** may change between releases; see the status at the top.

A label before `for`, `switch` or `select` names the statement for `break` and `continue` inside
nested loops, as in Go and JS:

```go
outer: for row in grid {
    for v in row {
        if v < 0 {
            continue outer                 // the next row
        }
        if v == target {
            console.log("found")
            break outer                    // both loops
        }
    }
}
```

```js
outer: for (const row of grid) {
  for (const v of row) {
    if (v < 0) {
      continue outer
    }
    if (v === target) {
      console.log('found')
      break outer
    }
  }
}
```

- **`break outer`** leaves the loop, the `switch` or the `select` labeled `outer`, and
  **`continue outer`** goes to the next iteration of the loop labeled so: a `switch` or a `select`
  has no iterations to go to.
- **Where labels are seen:** in the statement they label, not in the functions inside it, and not in
  the body of `go for`, whose parts run in workers; `go for` itself has no label for that reason.
- **The rules of Go:** a label that no `break` or `continue` uses is an error, and so is a label
  that an enclosing statement already has. Other statements, such as `if` or a block, have no
  labels.
- `outer:` can stand on its own line before the loop, as in Go.

