In this article let us find out what is the difference between the keywords ‘var’ and ‘let’ that are used to define a variable in TypeScript.
The variable which has been declared with the ‘var’ keyword will still belong to the same variable even though it has been declared again in another code block with another ‘var’ keyword. For example,
var item1 = <number> 1
if (item1 == 1) {
var item1 = 2 as number
console.log(`${item1}`) /* 2 */
}
console.log(`${item1}`) /* 2 */
The outcomes are as follows:-
2 2
As you can see that the above variables that are in different scopes produce the same outcome which means the ‘var’ keyword does not declare a different variable within the ‘if’ block but instead assigns the same previously declared variable again to another number.
In order to declare two variables with the same name in different scopes, you will need to use the ‘let’ keyword instead.
let item1 = <number> 1
if (item1 == 1) {
let item1 = 2 as number
console.log(`${item1}`) /* 2 */
}
console.log(`${item1}`) /* 1 */
The above program will show the following outcomes:-
2 1
As you can see nothing much has been changed but only the ‘var’ keyword has been replaced with the ‘let’ keyword to produce two totally different variables in two different scopes!