Variables in TypeScript

In the previous tutorial we saw what is data type, we even saw the candies example, In this post we’re going to see What are Variable, how do we use them.

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!!

You cannot just go ahead naming xyz to variables, TypeScript follows JavaScript rules to name the variables,

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:

  1. 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.
  2. 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.
  3. Class Scope: If a variable is declared inside the class then we can access that variable within the class only is called class scope.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s