Adventures on the edge

Learning new development technologies
    "When living on the bleeding edge - you sometimes have to bleed" -BillKrat

let and var in TypeScript

The advantage of the “let” keyword is that you cannot use a variable before it has been defined (safer).  In contrast “var” does not have to be defined.  The following will compile:

console.log('not defined = ' + notDefinedIsLegal);
var notDefinedIsLegal;

Note in image below [underlined in red] that “let” will complain "error TS2448: Block-scoped variable 'mustBeDefinedBeforeUse' used before its declaration"


In addition, "let" scopes to blocks. Below I define both variables in a block and the definition for the let is limited to the block of code it resides in - this is not the case with var as the output will demonstrate.

console.log('not defined = ' + notDefinedIsLegal);
var notDefinedIsLegal : string;

let mustBeDefinedBeforeUse = 'Hello World';
console.log('mustBeDefined = '+ mustBeDefinedBeforeUse);

    var notDefinedIsLegal = "legal!";
    let mustBeDefinedBeforeUse = "Goodbye World!!";
    console.log('[blockscoped] mustBeDefined = '+ mustBeDefinedBeforeUse);
    console.log('[blockscoped] notDefinedIsLegal = ' + notDefinedIsLegal);

console.log('mustBeDefined = '+ mustBeDefinedBeforeUse);
console.log('notDefinedIsLegal = '+ notDefinedIsLegal);

results in the following output:


Comments are closed