On this put up we’ll see how var key phrase in sort script is totally different from let key phrase. We are going to use quite simple program to clarify the distinction between var vs let key phrases in angular 2 typescript.
VAR Key phrase Utilization
We are going to write a easy program with var key phrase as give under
1 |
operate doSomething(){<br/> <br/> for(var i=0;i<5;i++){<br/> console.log(i);<br/> }<br/><br/> console.log('Lastly ' + i);<br/>}<br/><br/><br/>doSomething();<br/><br/> |
Run this under command to compile sort script
1 |
PS C:UsersAnilKumarts-hello> tsc code-main.ts |
Run the code-main.js file utilizing node.js
1 |
PS C:UsersAnilKumarts-hello> node code-main.js<br/>0<br/>1<br/>2<br/>3<br/>4<br/>Lastly 5<br/>PS C:UsersAnilKumarts-hello> |
Variable ‘i’ is asserted inside loop however nonetheless we will use it exterior loop which make its out there for different code as properly inside doSomething() operate.
LET Key phrase Utilization
We are going to change the key phrase var –> let as given under.
1 |
operate doSomething(){<br/> <br/> for(let i=0;i<5;i++){<br/> console.log(i);<br/> }<br/><br/> console.log('Lastly ' + i);<br/>}<br/><br/><br/>doSomething(); |
Once more compile the code as we did earlier.
1 |
PS C:UsersAnilKumarts-hello> tsc code-main.ts<br/>code-main.ts(9,30): error TS2304: Can't discover identify 'i'. |
Now we have compilation error which recommend variable ‘i’ isn’t seen exterior loop which means scope is restricted to nearest scope. We will this error in visible studio code as properly when writing code.
You may see exterior loop variable is marked error and you may see error message for those who hover mouse pointer on it.
Supply projectgeek.com