Sunday, September 29, 2024
Google search engine
HomeLanguagesJavascriptVariables in TypeScript

Variables in TypeScript

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 Identifier:Data-type = value;
  • var Identifier: Data-type;
  • var Identifier = value;
  • var Identifier;
  • Examples:

    Variable declaration Description
    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.

    Code #1:




    var global_var = 10         //global variable 
    class Geeks { 
       neveropen_var = 11;             //class variable 
       assignNum():void { 
          var local_var = 12;    //local variable 
       
    document.write("Global Variable: "+global_var)  
    var obj = new Geeks(); 
    document.write("Class Variable: "+obj.neveropen_var) 

    
    

    Output:

    Global Variable: 10
    Class Variable: 11
    

    RELATED ARTICLES

    Most Popular

    Recent Comments