Declaring a Variable

This lesson covers the archaic var that is supported in TypeScript and describes the cost of using this old fashion way to declare a variable. We will see how we can maximize the declaration with let and const as alternatives.

Declaring with var

Let’s get started with var. This has been the way to define variables since the inception of JavaScript. However, the release of ECMAScript2015 brought the declarations let and const, which fixed many of the drawbacks perpetuated in previous versions of ECMAScript. In many modern languages, declaring a variable is as simple as being alive in the scope where this one was defined.

For example, a variable declared in a conditional statement is only available inside the conditional statement – not before or after.

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.

Press + to interact
function varFunction(){
var x = "111";
if(true){
var x = "999"; // Variable x redefined
}
console.log(x);
}
varFunction()

As seen in the example, because the variable x is outside the closure of the if statement, the new declaration redefines x (line 4) and overrides its previous value (line 2).

However, the new definition is contained within the scope of the function. For example, trying to output x from outside the function will return undefined.

Press + to interact
var x;
function varFunction(){
var x = "111";
if(true){
var x = "999";
}
console.log(x);
}
varFunction()
console.log(x)

It is important to note that not declaring the variable x would result in TypeScript signaling that it Cannot find name x. However, if TypeScript is not strict: true, the code will signal an error but will ...