In this post we will see how var keyword in type script is different from let keyword. We will use very simple program to explain the difference between var vs let keywords in angular 2 typescript.
VAR Keyword Usage
We will write a simple program with var keyword as give below
function doSomething(){ for(var i=0;i<5;i++){ console.log(i); } console.log('Finally ' + i); } doSomething();
Run this below command to compile type script
PS C:\Users\AnilKumar\ts-hello> tsc code-main.ts
Run the code-main.js file using node.js
PS C:\Users\AnilKumar\ts-hello> node code-main.js 0 1 2 3 4 Finally 5 PS C:\Users\AnilKumar\ts-hello>
Variable ‘i’ is declared inside loop but still we can use it outside loop which make its available for other code as well inside doSomething() function.
LET Keyword Usage
We will change the keyword var –> let as given below.
function doSomething(){ for(let i=0;i<5;i++){ console.log(i); } console.log('Finally ' + i); } doSomething();
Again compile the code as we did earlier.
PS C:\Users\AnilKumar\ts-hello> tsc code-main.ts code-main.ts(9,30): error TS2304: Cannot find name 'i'.
We have compilation error which suggest variable ‘i’ is not visible outside loop that means scope is limited to nearest scope. We can this error in visual studio code as well when writing code.
You can see outside loop variable is marked error and you can see error message if you hover mouse pointer on it.
Leave a Reply