I will try to explain this by taking an example.
create a file main.ts
1
2
3
4
5
6
7
8
9
|
function printData(){
for(var i=0; i<5; i++){
console.log(i);
}
console.log('last value:' + i);
}
printData();
|
Now compile and run the compiled code like:
1
|
tsc main.ts | node main.js
|
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:
1
2
3
4
5
6
7
8
9
|
function printData(){
for(let i=0; i<5; i++){
console.log(i);
}
console.log('last value:' + i);
}
printData();
|
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:
1
|
tsc main.ts
|
It will give the error : 'can not find name i'.
However it will still generate the file main.js with the JavaScript code.
1
2
3
4
5
6
7
|
function printData(){
for(var i=0; i<5; i++){
console.log(i);
}
console.log('last value:' + i);
}
|
Because this JavaScript code is perfectly valid JavaScript code so now if you run this like:
1
|
node main.js
|
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.