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
- Identifiers and Keywords in TypeScript
- Data types in TypeScript
- Hello World in TypeScript
- TypeScript class
- Classes in TypeScript
- TypeScript Arrays
- TypeScript Tuples
- TypeScript Ambients Declaration
- TypeScript Union
- TypeScript String
- TypeScript Accessor
- Why use Question mark in TypeScript variable ?
- What are the differences between any vs Object in TypeScript?
- How to execute TypeScript file using command line?
- What is the difference between interface and type in TypeScript ?
- How to Import another TypeScript Files ?
- Difference between private keyword and private fields in TypeScript
- What is the difference between 'String' and 'string' in TypeScript ?
- How to Cast a JSON Object Inside of TypeScript Class ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.