TypeScript has introduced two new types of variable declarations let
and const
. Here let
is similar to var
in some respects and const
is an augmentation of let
and prevents re-assignment to a variable.
Here you will learn both types of variable declarations and why they're preferable over to var
.
This is similar to JavaScript variable declarations using var
keyword. For Example:
var a = 210; var message = "Some string;
The var
declarations are accessible anywhere within their containing function, module, namespace, or global scope.
function Display(setValue: boolean) { if (setValue) { var counter = 10; } return counter; //Accessible outside if block } Display(true); // returns '10' Display(false); // returns 'undefined'
Here, variable counter was declared within the if block, but still accessible outside the if block.
The let
variable declarations are similar to var
variable declarations. But still has some semantics key difference from var
. For Example:
let a = 210; let message = "Some string;
The let
variables are block-scoped variables and are not visible outside of their nearest containing block or for-loop.
function Display(setValue: boolean) { let x = 10; if (setValue) { let counter = 10; } return counter; //Not Accessible, Error : counter not exist here }
Here, variable counter was declared within the if block and not accessible outside the if block. But x declared in function block and is accessible anywhere within function block.
The const
variable declarations are another way of variable declaration and similar to let
but, const
value can not be changed. For Example:
const x = 9; const Customer = { fname: "Jimi", lname: "Scott", }
The const
follow the same scoping rules as let
, but you can't re-assign to them.
const x = 9; const Customer = { fname: "Jimi", lname: "Scott", } // Error : can not change Customer = { fname: "John", lname: "Wood" };
Here, variable counter was declared within the if block and not accessible outside the if block. But x declared in function block and is accessible anywhere within function block.