# Conditionals

## Basic `if` and `else`

If you store the builder object in a variable, you can use `if` and `else` statements like you would expect.

```
var builder = builder.from( "posts" );
if ( rc.recent ) {
    builder.orderBy( "published_date", "desc" );
}
var results = builder.get();
```

This works, but breaks chainability. A better way is to use the `when` helper method.

## `when`

| Name      | Type    | Required | Default                     | Description                                                                                                   |
| --------- | ------- | -------- | --------------------------- | ------------------------------------------------------------------------------------------------------------- |
| condition | boolean | true     |                             | The condition to switch on.                                                                                   |
| onTrue    | Closure | true     |                             | The callback to execute if the condition is true.  It is passed the `builder` object as the only parameter.   |
| onFalse   | Closure | false    | function( q ) { return q; } | The callback to execute if the conditions is false.  It is passed the `builder` object as the only parameter. |

We can rewrite the above query like so:

```
var results = builder.from( "posts" )
    .when( rc.recent, function( q ) {
        q.orderBy( "published_date", "desc" );
    } )
    .get();
```

Nice. We keep chainability this way and reduce the number of temporary variables we need.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://qb.ortusbooks.com/6.4.0/query-builder/conditionals.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
