Start learning free

LESSON 4 OF 348 · WELCOME TO TYPESCRIPT

Variables in TypeScript: let, const and Type Annotations

Lesson Read the full explanation

TL ; DR:

Variables are containers for storing values. You create a variable using the let keyword.

This is how you create a variable named car and initialize it with string "Toyota":

let car = "Toyota";

This is how you create a variable named experience and initialize it with number 3:

let experience = 3;


Full lesson:

Variables are containers for storing values. A piece of information / data lives in memory and we use a variable to store and descriptively label that data.


Variable creation:

We tell JavaScript to create or declare a variable by putting the keyword let in front of the variable's name, like so:

let name;

creates a variable named name.


Variable initialization:

We can initialize a variable to an initial value in the same line as it is created using the assignment operator (=). This code:

let name = "AlgoCademy";

creates a new variable named name and assigns it an initial value of "AlgoCademy".

When executing this code, JavaScript will allocate some memory, then it will store the string "AlgoCademy" in that memory and finally will attach this name label to that memory location.

You can think of this memory location as a box. In that box, we put string "AlgoCademy". Then, we put the label name on this box.


Accessing values in variables:

Now we can use this label anywhere in our program to access the value in that box. We can print it for example:

// We create and initialize two variables:
let name = "AlgoCademy";
let age = 10;

// We access the variables:
console.log(name);
console.log(age);

The output of this code is:

AlgoCademy
10

Undefined:

In the first piece of code, we have created the container name. That container was empty, we didn't put any data inside it.

In other words, we have created the variable name, but we haven't assigned any value to it yet.

And so, the output of this code:

let name;

console.log(name);

would be:

undefined

The JavaScript undefined property indicates that a variable has not been assigned a value, or not declared at all.

We'll learn much more about this in future lessons, but we want to avoid having undefined values in our programs as much as possible.


Important notice:

We almost never want to create a variable without initializing it! It's a bad coding practice and can cause a lot of problems.


Type annotations:

TypeScript lets you add an optional type annotation after a variable's name, separated by a colon. It tells the compiler exactly what kind of value the variable holds. You still use const and let just like in JavaScript.

let count: number = 5;
let isOn: boolean = true;
const car: string = "Toyota";

You'll see annotations like : number, : boolean, and : string throughout the coding tutorials.


Assignment
Follow the Coding Tutorial and let's create some variables.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · WELCOME TO TYPESCRIPT

    Variables in TypeScript, explained

    What a variable is

    A variable is a named container for a value. The value lives in the computer's memory, and the name is a label you use to find it again. Instead of repeating a value everywhere, you store it once and refer to it by name, which also makes the code easier to read.

    Creating and initializing

    You create, or declare, a variable with the keyword let followed by a name. You can give it a first value, initialize it, in the same statement with the assignment operator =:

    let car = "Toyota";
    let experience = 3;
    console.log(car, experience);
    
    Toyota 3
    

    Think of each variable as a labelled box: the box car holds the string "Toyota", and the box experience holds the number 3. Wherever you write the name afterwards, TypeScript uses the value inside.

    Type annotations

    TypeScript lets you state what kind of value a variable holds by writing a colon and a type after the name:

    let city: string = "Paris";
    let year: number = 2020;
    let isOn: boolean = true;
    const pi: number = 3.14;
    

    The three basic types are string for text, number for all numbers, whole or decimal, and boolean for true and false. If you initialize the variable, the annotation is optional, because TypeScript infers the type from the value: let year = 2020 is also a number. The lessons use annotations in many places to make the types visible.

    Once a variable has a type, the compiler rejects values of another type. Assigning "five" to a variable that holds a number is an error:

    error TS2322: Type 'string' is not assignable to type 'number'.
    

    The compiler reports the error, but a type error does not stop it from writing the JavaScript. If n was declared as a number and n = "five" is compiled and run anyway, the program prints five string, because the annotation is gone at run time. Treat the error as a bug to fix, not as something the program will protect you from.

    Annotations are checked when the program is compiled and then erased. The JavaScript that runs has no types, so an annotation does not convert a value or protect against a wrong value that arrives at run time, for example from parsed data.

    Changing a value: let and const

    A let variable can be given a new value later. The new value must match the type:

    let total: number = 10;
    total = total + 5;
    console.log(total);
    
    15
    

    A const variable cannot be reassigned, and the compiler reports Cannot assign to 'pi' because it is a constant if you try. Use const for values that should not change and let for values that will.

    Variables without a value

    A variable declared without a value holds undefined:

    let late;
    console.log(late);
    
    undefined
    

    This is almost never what you want. Initialize variables when you create them, so every name always holds a real value.

    Naming and a gotcha

    Names can contain letters, digits, _ and $, and cannot start with a digit. Capital letters matter, so Age and age are different variables. The usual style is camelCase, as in userName.

    The exercise

    The exercise creates two variables, one per line:

    1. Write let, then the name name, then a colon and string.
    2. Add = "Michael", with the value in double quotes, and a semicolon.
    3. On the next line, write let age: number = 31;. The number goes without quotes. "31" would be a string.

    The lesson's tests check for these two variables with exactly these names and values.

    Common mistakes

    • Quoting a number. let age: number = "31" is a type error.
    • Misspelling the name later. Using aniimal for a variable called animal gives an error, because the compiler can't find that name.
    • Declaring twice. A second let year in the same scope is an error. Assign with year = 2021 instead.

    Key takeaways

    • A variable is a named container for a value.
    • let declares a variable that can change, const one that cannot.
    • Annotations such as : string, : number and : boolean describe the type and are checked by the compiler only.
    • Always initialize variables.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free