In TypeScript, variable scopes can be broadly categorized into the following types:
-
Global Scope: Variables declared in the global scope are accessible throughout the code. This means that once declared in the global scope, a variable is usable within any function or class. For example:
typescriptlet globalVar = "I am a global variable"; function display() { console.log(globalVar); // Output: I am a global variable } display(); -
Function Scope: Variables declared inside a function are accessible only within that function, which is known as function scope. This includes variables declared with the
varkeyword. For example:typescriptfunction testFunctionScope() { var functionScopedVar = "I exist only in this function"; console.log(functionScopedVar); // Output: I exist only in this function } // console.log(functionScopedVar); // Error: functionScopedVar is not defined testFunctionScope(); -
Block Scope: TypeScript also supports block-level scope introduced in ES6, where variables declared with
letandconstare accessible only within the block where they are declared, such as inifstatements,forloops, or any block enclosed in{}. For example:typescriptfunction testBlockScope() { if (true) { let blockScopedVar = "I exist only in this block"; console.log(blockScopedVar); // Output: I exist only in this block } // console.log(blockScopedVar); // Error: blockScopedVar is not defined } testBlockScope(); -
Module Scope: In TypeScript, variables declared within a module (essentially any file) are accessible only within that module unless exported. This adheres to the ES6 module system. For example:
typescript// In moduleA.ts file export let moduleScopedVar = "I am available in any module that imports me"; // In another file import { moduleScopedVar } from './moduleA'; console.log(moduleScopedVar); // Output: I am available in any module that imports me
Understanding these different scopes is crucial for writing clear, maintainable code. They help you control variable visibility and lifetime, avoiding potential conflicts and errors.