What is Variable?
Variable is a name given to stored memory location. Baffled? Nup? Better you can go to next para…. If you’re still thinking What Am I talking? This explanation is for you– Suppose you stay in a 2 storey Building, and a building has 6 flats, 3 each floor. Now you live in Second Floor third flat so basically your flat number is 203, Which is the name(number) given to your flat. Similarly Building is your memory location, variables you store in a flat and you give them a name? ~EASY!!
Variable Declaration Rules:
- Variable names can contains alphabets both Upper-case as well as Lower-case and can contains digits too.
- Variable name cannot start with digit.
- No special characters are allowed except “_” and “$”.
Ways to Declare TypeScript Variables:
In TypeScript we can declare variable in 4 ways, Let us see them
var Identifier: Data-type = value var variableNumber: number = 12345 // Defined Number type explicitly and assign value. var Identifier: Data-type var variableNumber: number // The variable is set to undefined var Identifier = value var variableNumber = 12345 // The variable will infer the data type based on value. var Identifier var variableNumber // Set to undefined by default and type is Any.
Variable scopes in TypeScript:
Visibility and Accessibility of variables defines the scope. Scope means whether we are able to use the variable in specific part of the programs. Confused? No need to worry we will understand the same in detail below.
TypeScript has 3 Scopes:
- Global Scope: As the name says, global which means it can be accessed from anywhere in your code, if you declare any variable outside the programming construct we can can access it from anywhere in the code.
- Local Scope: As the name says, local which means within the block like methods, loops etc. Local variables are accessible only within the programming construct where they are declared.
- Class Scope: If a variable is declared inside the class then we can access that variable within the class only is called class scope.