Overview
To declare the variables in JavaScript or TypeScript, we often use var or let. Here, we will discuss the differences between both of the declarations.
var
When we declare variables using var:
- The declaration is processed before the execution.
- Variable will have function scope.
Code
- function CheckingScope() {
- var _scope = ‘Out’;
- console.log(_scope);
- if (true) {
- var _scope = ‘In’;
- console.log(_scope);
- }
- console.log(_scope);
- }
In the above code, we can find that when the variable is updated inside the if block, the value of variable "_scope" is updated to “In” globally.
let
When we declare variables using let:
- Variable will have block scope.
Code
- function CheckingScope() {
- var _scope = ‘Out’;
- console.log(_scope);
- if (true) {
- let _scope = ‘In’;
- console.log(_scope);
- }
- console.log(_scope);
- }
In the above code, we can find that when the variable is updated inside the if block, the value of variable "_scope" is not updated globally.
Reference
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let