Typescript Constants (Const)

Typescript constants are variables, whose values cannot be modified. We declare them using the keyword const. They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared. Const keyword is part of the es2015 (es6) specification of the javascript.

Declaring a const

We declare constants using the keyword const keyword

Example:

The initial value is a must

The initial value of the const must be specified along with the declaration.

Const is block scoped

The const is similar to the let keyword. They are local to the code block in which we declare them.

The left-hand side of an assignment cannot be a constant

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, it is just that the variable identifier cannot be reassigned.

So if you try to assign a new value to a constant it results in an error.

Similarly, if the const is an object.

Const is a read-only reference to a value

The const creates a Readonly reference to a value. Readonly reference is the key here. We cannot change the reference. It is immutable. But we can change the value of the properties it holds.

This is evident when you create an object as constant. You cannot assign a new object.

However, you can change the properties of objects.

The following is an example using arrays.

Cannot access before the declaration

Accessing the const before the initialization results in a ReferenceError. The variable in a “temporal dead zone” from the start of the block until the initialization.

Cannot Redeclare a const.

Trying to redeclare constant throws the following error. Uncaught SyntaxError: Identifier ‘MaxTry’ has already been declared”.

Summary

We recommend using const to declare variables. Use let if you need to change the value of the variable. But always remember the fact that the properties of the const can be changed if it is an object.

1 thought on “Typescript Constants (Const)”

  1. Indike Dassanayake

    Very good explanation.
    I am an absolute beginner to TS but have some experience in several languages.
    It was really easy to comprehend.
    One thing I would like to see is having links to get help on keywords in articles like this.
    e.g. I wanted to check what “splice” is but have to google again.
    Anyway, thanks for your valuable contribution.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top