Variable Scope in TypeScript

Variable Scope defines where the variable is defined and the area in which we can use the variable.

Variables are divided in three Scopes:

Global Scope
  • Global variables are declared outside all the functions and classes.
  • Generally we declare global variables at the starting of our program.
  • They can be accessed from anywhere within the code.
Class Scope
  • These variables are also called as fields.
  • These variables are declared within a class but outside any method.
  • They accessed by using the object of the class.
  • If these variables are declared static, then we do not have to create an object to access them. We can simply access them using class name.
Local Scope
  • These variables are declared within a method, loop etc. and they can be accessed within them only.
  • For example, if a variable is declared within a method, it can be access from within that method only. We cannot access it from outside that method.

Below is the example for various variable scopes:

var globalVar = 100;
class Values{
    classvar=200;
    static staticVar=50;

    localMethod():void{
        var localVar=300;
        console.log("Local Variable: " + localVar);
    }
}
var obj=new Values();
console.log("Global Variable:" + globalVar);
console.log("Class Variable: " + obj.classvar);
console.log("Static Variable: " + Values.staticVar);
obj.localMethod();

Below is the JavaScript conversion of the above code:

var globalVar = 100;
var Values = /** @class */ (function () {
    function Values() {
        this.classvar = 200;
    }
    Values.prototype.localMethod = function () {
        var localVar = 300;
        console.log("Local Variable: " + localVar);
    };
    Values.staticVar = 50;
    return Values;
}());
var obj = new Values();
console.log("Global Variable:" + globalVar);
console.log("Class Variable: " + obj.classvar);
console.log("Static Variable: " + Values.staticVar);
obj.localMethod();

Below is the output of above code using NodeJS Command prompt:

If you try to access a variable outside of its scope, it will give a compilation error:
Could not find symbol ‘localvar’

Related Articles
Compilation and Execution of TypeScript Code

Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Leave a comment

Design a site like this with WordPress.com
Get started