TypeScript Variable Declaration
In TypeScript, we use the let and const keywords to declare variables. This is consistent with modern JavaScript (ES6) practices. The var keyword is still available but generally not recommended because it has some scope issues.
1. Declaring Variables with let
let is used to declare a block-scoped local variable. This means the variable is only valid within the code block where it's declared (for example, an if statement, for loop, or function body).
Variables declared with let can have their values modified.
2. Declaring Constants with const
const is used to declare a block-scoped constant. Constants must be initialized when declared, and their value cannot be changed once assigned.
const declaration means the reference to the value is immutable. If the constant is an object or array, you cannot reassign it, but you can modify properties or elements inside the object or array.
3. Type Annotation
TypeScript allows you to explicitly specify a variable's type when declaring it, which is called "type annotation." The syntax is to add a colon (:) and the type name after the variable name.
Type annotations are optional. If you initialize a variable when declaring it, TypeScript will use type inference to automatically determine the variable's type.
Although type inference is convenient, explicitly adding type annotations is good practice in the following situations:
- When a variable is not immediately initialized.
- When a function's return value type is not obvious.
- When you want the code's intent to be clearer and more explicit.
Variable Scope
Scope determines which areas of code can access a variable.
- Block Scope: Variables declared with
letandconsthave block scope. They are only valid within the nearest containing code block ({...}). - Function Scope: Variables declared with
varhave function scope. They are visible throughout the entire function, regardless of which code block they're declared in. - Global Scope: Variables declared outside all functions and code blocks have global scope and can be accessed anywhere in the code.