TypeScript follows the same rules as JavaScript for variable declarations. Variables can be declared using:

  • var
  • let
  • const

The let declarations follow the same syntax as var declarations. but you have to know that, variables declared with let have a block-scope.

Block-scope means that the scope of let variables is limited to their containing block, e.g. function, if else block or loop block.

example :

let num1:number = 1; 
function letDeclaration() { 
    let num2:number = 2; 

    if (num2 > num1) { 
        let num3: number = 3;

    while(num1 < num2) { 
        let num4: number = 4;

    console.log(num1); //OK
    console.log(num2); //OK 
    console.log(num3); //Compiler Error: Cannot find name 'num3'
    console.log(num4); //Compiler Error: Cannot find name 'num4'


Advantages of using let over var :

  • Block-scoped let variables cannot be read or written to before they are declared.
  • Let variables cannot be re-declared

Const :

Const variables must be declared and initialized in a single statement. Separate declaration and initialization is not supported. Also its value cannot be changed !!

Laisser un commentaire