In TypeScript, variables will represent storage locations and these are useful to store/hold the data to use it in applications to perform required actions.
In TypeScript, we can use var
, let
and const
keywords to define the variables same like JavaScript and the variable declaration in TypeScript will follow the same rules as JavaScript.
Following are the rules which you need to follow before you declare and define variables in TypeScript.
var
, break
, any
, if
, switch
, etc. for the variable name.In TypeScript, the variables declaration and initialization with var
, let
and const
keywords are same but the only difference is the scope and usage of the variables will vary based on the defined keyword.
In JavaScript ES6, the let
and const
keywords are introduced to fix the problems of var
keyword. As discussed, the TypeScript will support all the features of JavaScript so automatically it will support both let
and const
keywords.
Following are the syntaxes of declaring and initializing the variables in typescript.
[Keyword] [Variable Name] = [Value];
[Keyword] [Variable Name];
[Keyword] [Variable Name]: [Type Annotation] = [Value];
[Keyword] [Variable Name]: [Type Annotation];
If you observe the above syntaxes, we used different terms to declare and initialize the variables in typescript. To know more about each item, check the following info.
var
, let
or const
to define the scope and usage of variable.Now, we will learn how to declare and define the variables in TypeScript with different keywords such as var
, let
and const
with examples.
Following is the example of declaring and defining the variables with var
keyword in typescript.
var uname = "Suresh Dasari";
var ulocation: string = "Hyderabad";
var marks = 400;
var percentage: number = 45.6;
console.log("Name:" + uname);
console.log("Location:" + ulocation);
console.log("Marks:" + marks);
console.log("Percentage:" + percentage);
When we compile the above code, the typescript compiler will generate the following JavaScript code.
var uname = "Suresh Dasari";
var ulocation = "Hyderabad";
var marks = 400;
var percentage = 45.6;
console.log("Name:" + uname);
console.log("Location:" + ulocation);
console.log("Marks:" + marks);
console.log("Percentage:" + percentage);
By default, in JavaScript var
keyword is useful to declare the variables. The above example will return the result like as shown below.
Name:Suresh Dasari
Location:Hyderabad
Marks:400
Percentage:45.6
We can also declare the variables inside of functions using var
keyword and we can access those variables in other functions like as following.
function a() {
var x = 15;
return function b() {
var y = x + 20;
return y;
}
}
var c = a();
var result = c();
console.log(result); // returns '35'
If you observe the above example, we created variable “x” and we are able to access the same variable (x) inside of another function.
Generally, the var
variables are accessible anywhere within their containing function, module, namespace, or global scope regardless of the containing block.
Following is the example of declaring and using the var
variables in TypeScript.
function printNumber(x: number, isActive: boolean) {
if (isActive) {
var y = x + 1000;
}
if (x > 2) {
var z = x + 10;
}
console.log(x); // 1
console.log(y); // undefined
console.log(z); // undefined
}
printNumber(1, false);
If you observe the above code snippet, we created printNumber function with x and isActive parameters and printing different variables (x, y, z) value.
If isActive variable value is true, then it will execute the statements which are inside of the condition. Same way, if x value is greater than 2 then it will the statements inside of the condition.
When we execute the above example, we will get the result like as shown below.
1
undefined
undefined
Even though the declaration of var
variables inside of the condition, we are able to access the values of variables within the function that is called function-scoping.
As discussed, in ES6 the let
keyword introduced to fix the problems of var
variables and to limit the access of variables to block level.
Same like var
, you can use let
keyword to define the let
variables. Following is the example of declaring and defining the variables with let
keyword in typescript.
let uname = "Suresh Dasari";
let ulocation: string = "Hyderabad";
let marks = 400;
let percentage: number = 45.6;
console.log(uname); // Suresh Dasari
console.log(ulocation); // Hyderabad
console.log(marks); // 400
console.log(percentage); // 45.6
If you observe the above code snippet, there is no difference in variables declaration with var
and let
keywords but the key difference is the scope of variables access.
Unlike var
variables, the let
variables will use block-scoping or lexical scoping that means the let
variables scope is limited to the specified block and it will provide type safety. So in typescript it’s always recommended to declare the variables using let
keyword.
Following is the example of declaring and using the let
variables in TypeScript.
function printNumber(x: number, isActive: boolean) {
if (isActive) {
let y = x + 1000;
}
if (x > 2) {
let z = x + 10;
}
console.log(x); // 1
console.log(y); // Error: Cannot find name 'y'
console.log(z); // Error: Cannot find name 'z'
}
printNumber(1, false);
If you observe the above code snippet, we created printNumber function with x and isActive parameters and printing different variables (x, y, z) value.
If isActive variable value is true, then it will execute the statements which are inside of the condition. Same way, if x value is greater than 2 then it will the statements inside of the condition.
When we try to execute the above program, we will get the compile-time errors like as shown below.
The compile errors occurred because we tried to access the variables (y, z) outside of the defined blocks. As discussed, the let
variable's scope is limited to the defined blocks. So, we will get compile-time errors when we try to access the let
variables outside of the scope.
Another thing, the blocked-scope let
variables will not allow to read/write before they actually declared.
Following is the example of using the variables before they actually declared in typescript.
console.log(x); // Block-scoped variable 'a' used before its declaration.
let x = 1;
console.log(y); // undefined
var y = 10;
When we execute the above program, the typescript compiler will throw compile-time error because we are trying to use let
variable before actually declared but we can use var
variables before they declared.
In typescript, the let
variables cannot be re-declared in the same scope but var
variables can be re-declared.
In case, if we re-declare let
variables in the same scope we will get the compile-time errors but for var
variables it didn’t matter how many times you declare the variables, you will get only one.
Following is the example of re-declaring the let
and var
variables in typescript.
let msg = "Welcome"; // OK
let Msg = "to"; // OK
let msg = "Tutlane"; // Error: Cannot re-declare block-scoped variable 'msg'
let Msg = "Tutorials"; // Error: Cannot re-declare block-scoped variable 'Msg'
var uname = "suresh";
var uname = "Rohini";
var uname = "Trishi";
console.log(uname); // Trishi
In the above example, the TypeScript compiler will consider the let
variables msg and Msg are different because the typescript is case-sensitive but it will throw compile-time error for the let
variables which match with the same name and case.
For var
variables, it didn’t matter how many times you declare the variables, the TypeScript compiler will consider only the latest var
variable.
If required, you can use let
variables with the same name and case in different blocks as shown below.
function printNumber(x: number, isActive: boolean) {
let y = 1;
if (isActive) {
let y = x + 1000;
console.log(y); // 1003
}
if (x > 2) {
let y = x + 10;
console.log(y); // 13
}
console.log(y); // 1
}
printNumber(3, true);
If you observe the above code snippet, we re-declared the variable y for multiple times in different block-scope.
When we compile and execute the above program, we will get the result as shown below.
1003
13
1
In typescript, we will get the compile-time errors when we re-declare variables in the following cases.
function addnumbers(x: number) {
let x = 100; // Error: Duplicate identifier 'x'
}
function subnumbers(){
let x = 100;
var x = 100; // Error: Cannot re-declare block-scoped variable 'x'
}
If you observe the above code snippet, we got compile-time error when we re-declare the variable that was already defined as an argument of function and when we define the same variable (x) with both let
and var
keywords.
As discussed, in ES6 the const
keyword was introduced along with let
keyword to fix the problems of var
variables.
The const
variables will behave same as let
variables but the only difference is the const
variable value cannot be changed once assigned.
Same like var
and let
declarations, you can use const
keyword to define the const
variables. Following is the syntax of declaring the const
variables.
const [Variable Name] = [Value];
const [Variable Name]: [Type Annotation] = [Value];
The const variables must be initialized during the declaration itself. Following is the example of declaring and defining the variables with const keyword in typescript.
const uname = "Suresh Dasari";
const ulocation: string = "Hyderabad";
const marks: number = 400;
marks = 500; // Error: Cannot assign to 'marks' because it is a constant
const percentage: number; // Error: 'const' declarations must be initialized
percentage = 78;
If you observe the above const
variables declaration, when we try to re-assign the value or declaring the const
variables without initialization, we got the compile-time errors.
The const
variables are having the same scoping rules as let
variables but you cannot re-declare or reassign const
variables.
In case, if you want to modify const
variable values you can do it via object properties like as shown below.
const lcount=1;
const user = {
name: "Suresh",
laps: lcount,
}
// Error: Cannot assign to 'user' because it is a constant
user = {
name: "Rohini",
laps: lcount
};
// all "okay"
user.name = "Rohini";
user.name = "Trishi";
user.laps++;
This is how we can declare and initialize variables in typescript using var
, let
and const
keywords based on our requirements.