The Difference between var and let in typescript



 The Difference between var and let in typescript


var:-

  • The var statement is used to declare a variable in JavaScript and TypeScript. A variable declared with the var keyword is defined throughout the program.

  • That is var has global scope or function scope, the var variable can be declared after the variable is actually used. This characteristic is called Hoisting, and it can be understood through an example.

Example


    x = "Hii Bobby";
    console.log(x);
    var x = "Hello...";
    console.log(x);


Output:-

E:\Visual code\typescript>tsc demo.ts

E:\Visual code\typescript>node demo
Hii Bobby
Hello...

     var also support re-declaring of the variable, for example:

Example


    var x = 10;
    if(x==10)
    {
        var x = 20;
        console.log(x);
    }
    console.log(x);

Output:-

E:\Visual code\typescript>tsc demo.ts

E:\Visual code\typescript>node demo   
20
20

let:-

  • The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. 
  • The let keyword can enhance our code readability and decreases the chance of programming error. A variable declared with the let keyword is limited to the block-scoped only.
  • The let keyword does not support Hoisting like var, we can see it in above code:

Example


    x = "Hii";
    console.log(x);
    let x = "Hello";
    console.log(x);



Output:-

E:\Visual code\typescript>tsc demo.ts
demo.ts:1:1 - error TS2448: Block-scoped variable 'x' used before its declaration.

1 x = "Hii";
  ~

  demo.ts:3:5
    3 let x = "Hello";
          ~
    'x' is declared here.

demo.ts:2:13 - error TS2448: Block-scoped variable 'x' used before its declaration.

2 console.log(x);
              ~

  demo.ts:3:5
    3 let x = "Hello";
          ~
    'x' is declared here.


Found 2 errors.

Here these two errors are caused due to x as it was declared using let keyword and let does not support hoisting.

  • let does not support re-declaring, but it updates the variable for the specified block.
Example

    
    let x = 10;
    if(x==10)
    {
        let x = 20;
        console.log(x);
    }
    console.log(x);

Output:-

E:\Visual code\typescript>tsc demo.ts

E:\Visual code\typescript>node demo   
20
10

Thank you for reading my blog, if you intend to write down your thoughts, you are more than welcome.
~ Bobby.

Comments

Post a Comment

Popular posts from this blog

Best Remote Developer Job Websites in 2026