Declaring with var

The most basic way to declare a variable is by using the keyword var.  It is the oldest declaration, but the least-preferred way because of some quirks. The main issue with var is that it gets declared in the execution context, which means inside the function scope or at the global scope. If, by accident a value is assigned to a variable not explicitly declared with var, then the scope of the variable is at the global scope. Here is an example:

function f1(){
a = 2; // No explicit "var", hence global scope instead of function scope
}

A var declaration can be made stricter with the strict mode in JavaScript so that TypeScript can turn on every file automatically by using alwaysStrict in its compiler's options. Otherwise, you must remember that var–declared variables are created before the execution of the code. Variables without the keyword var do not exist until the code assigning them is executed. In JavaScript, it's possible to assign a variable without declaring, which is not the case with TypeScript:

a = 2; // Won't create a variable in TypeScript

While TypeScript can protect against an undeclared variable, it does not protect a var declaration against the side effect of hoisting. The issue comes from JavaScript, where a declaration with var is processed before other pieces of code, which brings the variable declaration to the top of the scope (function or global). The subtlety is that the declaration is moved up, but not the initialization. That being said, TypeScript will not let you use a variable defined under its usage:

console.log("Test", a); // Won’t allow to use the variable in TypeScript
var a = 2;

Finally, var lets you define the variable that overrides the initial declaration or initialization more than once:

var a = 2;
var a = 23;

Generally, the use of var is a dated way to declare a variable. With TypeScript, there is a big incentive to rely on let or const because you can generate an older ECMAScript version that will generate var but in a proper and valid format.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.162.204