Start learning free

LESSON 13 OF 348 · VARIABLES

Constants in TypeScript: const Variables and Reassignment

Lesson Read the full explanation

There is a special type of variable in TypeScript, which is called constant.

A constant is a variable that we do not want to change the value of during the whole program.


Creation:

You create a const variable just like you create a normal one, but using the word const instead of let:

const ourName = "AlgoCademy";

console.log(ourName); // Output: AlgoCademy

Reassignment not allowed:

However, a const variable cannot be reassigned because it is constant. If you try to reassign a const variable, you'll get an error.

For example, this code:

const ourName = "AlgoCademy";

ourName = "Andy"; // Here is the problem

would produce error TS2588: Cannot assign to 'ourName' because it is a constant.


Must be initialized:

Constant variables must be initialized when declared. If you try to declare a const variable without a value, you'll get an error.

For example, this code:

const ourName;

would produce error TS1155: 'const' declarations must be initialized.


Usage:

It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?

The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.

This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.

Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:

const companyName = "Apple";
const foundingDate = "April 1st, 1976";
const founderName = "Steve Jobs";

Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.

I bet you wouldn't love it if a Junior Developer was able to do this successfully:

companyName = "Microsoft";
founderName = "Bill Gates";

But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.


Assignment
Follow the Coding Tutorial and let's work with constants!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · VARIABLES

    Constants in TypeScript, explained

    What a constant is

    A constant is a variable whose value you do not want to change while the program runs. You create one with the keyword const instead of let:

    const pi = 3.14;
    let radius = 2;
    console.log(pi * radius * radius);
    
    12.56
    

    Reading a const works exactly like reading any other variable. The only difference is what you are allowed to do afterwards.

    Reassignment is an error

    Once a const has its value, assigning to it again is rejected:

    const pi = 3.14;
    
    pi = 5;
    
    console.log(pi);
    

    The compiler reports error TS2588: Cannot assign to 'pi' because it is a constant. The JavaScript that tsc still writes then fails at run time: the assignment line throws TypeError: Assignment to constant variable. and the program stops there. Compound assignments such as pi += 1 are rejected for the same reason.

    Constants must start with a value

    A let variable can be declared first and filled in later. A const cannot, because it would then never be allowed to receive a value:

    const ourName;
    

    The compiler reports error TS1155: 'const' declarations must be initialized. Always give the constant its value on the line that declares it. Like any other variable, a name can be declared only once in the same scope, so a second const pi is also an error.

    Why limit yourself?

    Constants can look like variables with less freedom. The restriction is the point. When you mark a value as const, you tell the compiler and every other reader that this binding is never going to change. In a large program with many authors, the compiler then stops anyone from changing it by accident. A value such as a tax rate, a maximum size or a configuration setting should be a const. A good habit is to start every variable as const and switch to let only when you find you must reassign it.

    const fixes the binding, not the contents

    A const variable always points to the same value, but if that value is an array or an object, its contents can still change:

    const list = [1, 2];
    list.push(3);
    console.log(list);
    
    const person = { name: "Ann", age: 30 };
    person.age = 31;
    console.log(person);
    
    [ 1, 2, 3 ]
    { name: 'Ann', age: 31 }
    

    What you cannot do is point list at a different array with list = [3]. For numbers, strings and booleans the difference never shows, since those values cannot be changed in place.

    Naming constants

    Constants follow the same naming rules as other variables, so camelCase works: maxRetries. Many programmers write fixed, program-wide values in capitals with underscores, such as MAX_RETRIES, to make them stand out. Either style is fine if you use it consistently. Whatever you choose, the name should say what the value means, because a constant is read far more often than it is written.

    Types with const

    You can annotate a constant like any variable, for example const player: string = "Alice";. Without an annotation, TypeScript infers the type from the value, and the checks are the same.

    The lesson's exercise

    The starter program declares pi as a constant, then tries to change it:

    const pi = 3.14;
    
    pi = 5;
    
    console.log(pi);
    
    1. Read the error. It says pi is a constant and cannot be assigned to. It points at the line pi = 5;.
    2. Remove that line. A const has one value for its whole life, so the only fix is to delete the assignment.
    3. Keep the declaration and the print. They are correct.
    const pi = 3.14;
    
    
    
    console.log(pi);
    

    The program now prints 3.14. The blank lines left behind do nothing. If a value really has to change, the right fix is to declare the variable with let, but that is not what this exercise asks for.

    Key takeaways

    • Declare constants with const and give them a value immediately.
    • Reassigning a const is a compile error, TS2588.
    • Declaring a const without a value is an error, TS1155.
    • const protects the binding, not the inside of an array or object.
    • Prefer const, and use let only for values that change.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free