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. ...