# 03.iv Tail-call optimization

ES6 включает в себя поддержку оптимизации хвостовых вызовов. Однако это в стандарте, на деле стоит смотреть какой из браузеров поддерживает эту функциональность. Оптимизация хвостовых вызовов выполняется только в строгом режиме.

Оптимизация хвостовых вызовов возможна при условии, оптимизируемый вызов находится в хвостовой позиции, если:

* Вызов функции является последним выражением функции;
* Вызовы функции находятся в тернарном операторе (`? :`);
* Логический И (`||`);
* Логический ИЛИ (`&&`);
* Оператор запятой (`,`);

Тогда точка возврата в родительскую функцию уже не нужна и фрейм этой функции может быть сброшен со стека.

В ES6 не имеет значения какую именно функцию вы вызываете:

* Функию
* Метод
* Прямой вызов метода
* Косвенные вызовы метода

```javascript
// Both f() and g() are in tail position.
const a = x => (x ? f() : g());

// f() is not in a tail position, but g() is in a tail position.
const a = () => f() || g();

// f() is not in a tail position, but g() is in a tail position.
const a = () => f() && g();

// f() is not in a tail position, but g() is in a tail position.
const a = () => (f(), g());
```

Отдельные вызовы функций не находятся в хвостовой позиции:

```javascript
function foo() {
  bar(); // this is not a tail call in JS
}

function foo() {
  bar();
  return undefined;
}

// Should be
function foo() {
  return bar(); // tail call
}
```


---

# 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://strctr.gitbook.io/programming/01-languages/javascript/01-language/c-functions/c1-functions/03.iv-tail-call-optimization-es6.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.
