Variable: Variable is a named place in memory where some data/value can be stored. According to the word variable, it can be said that the value of a variable can be changed/vary. While declaring a variable, some rules have to be followed:
- Variable names can contains alphabets both Upper-case as well as Lower-case and digits also.
- Variable name cant start with digit.
- We can use _ and $ special character only, apart from these other special characters are not allowed.
Variable declaration: We can declare a variable in multiple ways like below:
|var name:number = 10;||Here name is a variable which can store only Integer type data.|
|var name:number;||Here name is a variable which can store only Integer type data. But by
default its value set to undefined.
|var name = 10;||Here while declaring variable we are not specifying data-type. Therefore
compiler decide its data type by seeing its value i.e. number here.
|var name;||Here while declaring variable we are not specifying data-type as well as
we are not assigning any value also. Then compiler takes its data type
as any. Its value is set to undefined by default.
Variable scopes in TypeScript:Here scope means the visibility of variable. The scope defines that we are able to access the variable or not. TypeScript variables can be of the following scopes:
- Local Scope:As the name specified, are declared within the block like methods, loops etc. Local variables are accessible only within the construct where they are declared.
- Global Scope:If the variable is declared outside the construct then we can access the variable anywhere. This is known as Global Scope.
- Class Scope:If a variable is declared inside the class then we can access that variable within the class only.
Global Variable: 10 Class Variable: 11