Variables
Variables
Variable Scope:
Variable scope refers to the region or context of the code where a variable is
accessible. The scope determines where in your code a variable can be used and
accessed. TypeScript supports two main types of variable scope: global scope and
local scope.
1. Global Scope:
Variables declared outside of any function or block have global scope. They
are accessible throughout the entire program.
// Gloabal Scope
function myFunc(){
console.log(globalVar) // Accessible within Functions
myFunc();
console.log(globalVar); // Accessible outside functions
2. Local Scope:
Variables declared inside a function or block have local scope. They are only
accessible within the function or block where they are declared.
// Local Scope
console.log("Local Scope of Variable");
function myFunc1(){
let localVar: number = 20;
const constVar: boolean = true;
console.log(localVar) // Accessible within Functions
console.log(constVar); // Accessible within the function
}
myFunc1();
// console.log(localVar); // Error: localVar is not defined outside the function
// console.log(constVar); // Error: constVar is not defined outside the function
Block Scope:
Variables in TypeScript have block-level scope when declared with let and
const, which means they are only accessible within the block (enclosed by curly
braces) where they are declared.
Variables declared with let and const also have block-level scope when
declared inside curly braces ({}).
// Block Scope
console.log("Block Scope of Variable");
if (true) {
let blockVar: number = 42;
const blockConst: string = "Block Scope";
console.log(blockVar)
console.log(blockConst)
}
Data Storage:
Variables store data values that can be used and manipulated throughout the
program.
Manipulating Data:
Code Readability:
Descriptive variable names enhance code readability, making it easier for developers
to understand the purpose of a variable and the data it holds.
Flexibility:
Variables make your code more flexible by allowing you to change values
dynamically during the execution of the program.
Type Annotations:
Code Organization: