# const

`const` is a very welcomed addition offered by ES6 / TypeScript. It allows you to be immutable with variables. This is good from a documentation as well as a runtime perspective. To use const just replace `var` with `const`:

```typescript
const foo = 123;
```

> The syntax is much better (IMHO) than other languages that force the user to type something like `let constant foo` i.e. a variable + behavior specifier.

`const` is a good practice for both readability and maintainability and avoids using *magic literals* e.g.

```typescript
// Low readability
if (x > 10) {
}

// Better!
const maxRows = 10;
if (x > maxRows) {
}
```

## const declarations must be initialized

The following is a compiler error:

```typescript
const foo; // ERROR: const declarations must be initialized
```

## Left hand side of assignment cannot be a constant

Constants are immutable after creation, so if you try to assign them to a new value it is a compiler error:

```typescript
const foo = 123;
foo = 456; // ERROR: Left-hand side of an assignment expression cannot be a constant
```

## Block Scoped

A `const` is block scoped like we saw with [`let`](/typescript/future-javascript/let.md):

```typescript
const foo = 123;
if (true) {
    const foo = 456; // Allowed as its a new variable limited to this `if` block
}
```

## Deep immutability

`const` хороши работает с объектными литералами, поскольку речт идет о защите "ссылки на переменную":

```typescript
const foo = { bar: 123 };
foo = { bar: 456 }; // ERROR : Left hand side of an assignment expression cannot be a constant
```

Однако он по-прежнему позволяет изменять свойства объектов, как показано ниже:

```typescript
const foo = { bar: 123 };
foo.bar = 456; // Разрешено!
console.log(foo); // { bar: 456 }
```

## Отдавайте предпочтение const

Всегда используйте `const`, если Вы не планируете либо лениво инициализировать переменную, либо переопределять ее (для таких случаев используйте `let`).


---

# 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://sudevgeny.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.
