> For the complete documentation index, see [llms.txt](https://artfulbits-se.gitbook.io/typescript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://artfulbits-se.gitbook.io/typescript/future-javascript/const.md).

# const

Константи.

`const` є дуже бажаним доповненням, запропонованим ES6/TypeScript. Це дозволяє вам створювати змінні, значення которих не можно змінити. Це добре як з точки зору документації, так і з точки зору часу виконання. Щоб використовувати const, просто замініть `var` або `let` на `const`:

```ts
const foo = 123;
```

> Синтаксис TS набагато кращий (IMHO), ніж у інших мовах, які змушують користувача вводити щось на зразок `let constant foo` , тобто змінна + специфікатор поведінки.

`const` є хорошою практикою як для зручності читання, так і для підтримки та уникає використання *magic literals* ("магічних" значень), наприклад

```ts
// Низька читабельність та не зрозуміло, чому саме 10?
if (x > 10) {
}

// Краще!
const maxRows = 10;
if (x > maxRows) {
}
```

## const declarations must be initialized

ВАЖЛИВО! Константа повинна отримати значення при створені.

Нижче наведено помилку компілятора:

```ts
const foo; // ПОМИЛКА: необхідно ініціалізувати оголошення const
```

## Left hand side of assignment cannot be a constant

Константи є незмінними після створення, тому якщо ви спробуєте призначити їм нове значення, це буде помилкою компілятора:

```ts
const foo = 123;
foo = 456; // ПОМИЛКА
```

## Block Scoped

`Const` має блочну область видимості , як ми бачили з [`let`](/typescript/future-javascript/let.md):

```ts
const foo = 123;
if (true) {
    const foo = 456; // Можливо, тому що це інша знінна foo
}
```

## Deep immutability

`const` також працює з об’єктними літералами, в цьому припаді незмінною є *reference* (посилання) на змінну:

```ts
const foo = { bar: 123 };
foo = { bar: 456 }; // // ПОМИЛКА: не можна присвоїти змінній інший обʼєкт
```

Однак він все ще дозволяє змінювати властивості об’єктів, як показано нижче:

```ts
const foo = { bar: 123 };
foo.bar = 456; // Allowed!
console.log(foo); // { bar: 456 }
```

## Prefer const

Завжди використовуйте const , якщо ви не плануєте пізніше ініціалізувати змінну, або виконати перепризначення (використовуйте let для таких випадків).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://artfulbits-se.gitbook.io/typescript/future-javascript/const.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.
