TypeScript Variables

Variable is a name of identifier which is capable to hold some value and reference. Value of variable are access by its name. The typeScript variable is based on the data type. Which are as follows.

Data Type Overview
number TypeScript supports 64 bit numbers.
boolean Represents a boolean value either true or false
string String is combination of single and more characters.
void Its used for functions that return nothing
null Represents no value or null value of objects

let and var keyword is used to declare variable in typescript. Here let indicate constant variable the value are never change. and var keyword are used to declare a mutable variable. Its syntax as follows.

// Declaring variable without value
var variableName : dataType ;
// Variable with initial value
let/var variableName : dataType = initialValue;

For example, let's create some variables using this data type.

// Declare string variable
var name: string ; 
// Declare number variable
var price: number ;
// Declare boolean variable
var status: boolean  ;

// Display default value of variable 
console.log("name : ", name);
console.log("price : ", price);
console.log("status : ", status);

// Change variable value
name  = "ABC";
price = 342.45;
status = true;

// Display variable value
console.log("name : ", name);
console.log("price : ", price);
console.log("status : ", status);
name :  undefined
price :  undefined
status :  undefined
name :  ABC
price :  342.45
status :  true

Variable Scope

There are three types of variable scopes are possible in typescript language.

Local Scope: This type of variable define within function and blocks. They are cannot access outside the function.

Global Scope: This type of variable define outside the function and its can be access all over the source code.

Class Scope : This is instance and field variable of class which is access by execute the class method and directly accessed by objects.

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment

© 2021, kalkicode.com, All rights reserved