What is the difference in let and var in typescript

I will try to explain this by taking an example.

create a file main.ts

Now compile and run the compiled code like:

 Output will be:

0
1
2
3
4
last value: 5

here value of i at the end is 5.

This is the issue of declaring a variable with var keyword. we have declared value of i inside the for block but it is also available outside the for block or it is available inside the whole function body.

if you declare the variable with let keyword.like:

It will immediately give a compilation error say 'can not find name i' and you will catch this error at compile time. This is the beauty of Typescript.

Now if you still compile this file:

It will give the error : 'can not find name i'.

However it will still generate the file main.js with the JavaScript code.

Because this JavaScript code is perfectly valid JavaScript code so now if you run this like:

it will give the same output:

0
1
2
3
4
last value: 5

so using let doesn't stop the compilation but we can catch the issue at compile time.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *