DEV Community

Cover image for Typescript : Variables
Brandon Damue
Brandon Damue

Posted on

Typescript : Variables

This post is the second part of the series Learn Typescript and we will be about all the nitty gritty of variables in TypeScript.

What are Variables?

A variable is a temporary data container that stores a value in memory while the application is running.

Declaring a Variable

I am going to start by covering the archaic var that is supported in TypeScript and describes the cost of using this old school way of declaring variables. I will also talk about how you can maximize the declaration with let and const as alternatives.

Declaring a Variable with var

Starting with var. This has been the way to define variables since the inception of JavaScript. However, the release of ES6 brought the declarations let and const, which fixed many of the drawbacks caused by var in previous versions of ECMAScript.

One issue with var is that the location of a variable makes it unpredictable. A variable declared using var is function-scoped when declared inside a function, but global-scoped when declared outside of a function. Also, var does not stop you from redefining the same variable, which overrides the initial declaration or initialization.

function varFunction(){     
    var x = "111";    
    if(true){             
        var x = "999"; // Variable x redefined   
    }     
    console.log(x); 
}
varFunction();
Enter fullscreen mode Exit fullscreen mode

Note that not declaring the variable x would result in TypeScript signaling that it Cannot find name x.

Declaring with let

The keyword let comes to the rescue by setting the lifespan of the variable at the block where it was declared that the variable is accessible only in the scope in which it was declared.

For example, if you declare a variable with let within an if statement, the variable will not be accessible as soon as the execution leaves the if block. This rule is true for a function, a loop, and a class. In the case of loops, if you are defining a for loop and you define the iterative i, this one should use let which allows modifying its values while being only available for the loop.

Declaring with const

The keyword const (short for constant) is similar to let in terms of the scope of its lifespan. However, it can only be initialized once: in its declaration. The restriction is powerful because it not only syntactically indicates that the purpose is not to change its value, but TypeScript will also ensure that no value can be set. It’s important to understand that if you have a constant object, the value of that object cannot change.

const x: string = "111";
x = "this won't compile";
Enter fullscreen mode Exit fullscreen mode

Note: The above code is expected to throw an error as explained

Top comments (0)