Introduction
In this chapter, we will learn about the let keyword in TypeScript. The let keyword is used to declare variables that are only accessible within the block where they are defined. This helps in writing clean and error-free TypeScript code.
Table of Contents
- Definition
- Syntax
- Block Scope
- Redeclaration
- Temporal Dead Zone
- Conclusion
Definition
The let keyword declares a variable that is block-scoped. This means the variable is only available within the block where it is defined. This is different from the var keyword, which declares a variable that is function-scoped or globally scoped.
Syntax
Syntax
let variableName: type = value;
Example
Here, we declare a variable age using let. Initially, age is set to 25. We then change its value to 26 and log it to the console.
let age: number = 25;
age = 26; // Allowed
console.log(age); // Output: 26
Block Scope
Variables declared with let are only accessible within the block where they are defined. A block is a section of code enclosed in curly braces {}.
Example
In this example, message is declared inside an if block. It is accessible within the block but not outside of it.
if (true) {
let message: string = "Hello, TypeScript!";
console.log(message); // Output: Hello, TypeScript!
}
// console.log(message); // Error: Cannot find name 'message'.
Redeclaration
Variables declared with let cannot be redeclared within the same block scope. This helps prevent errors and makes the code clearer.
Example
In this example, name is declared using let and then reassigned a new value. Trying to redeclare it within the same block will result in an error.
let name: string = "Ramesh";
// let name: string = "Suresh"; // Error: Cannot redeclare block-scoped variable 'name'.
name = "Suresh"; // Allowed
console.log(name); // Output: Suresh
Temporal Dead Zone
The temporal dead zone (TDZ) is the time between entering the scope where the variable is declared and the point where the variable is actually declared. Accessing a variable in the TDZ results in a ReferenceError.
Example
In this example, accessing myVar before its declaration will result in an error due to the temporal dead zone.
console.log(myVar); // Error: Cannot access 'myVar' before initialization
let myVar: number = 10;
Conclusion
In this chapter, we covered the let keyword in TypeScript, including its definition, syntax, block scope, redeclaration rules, and the temporal dead zone. Understanding the let keyword is important for writing clean, maintainable, and error-free TypeScript code. In the next chapter, we will explore the const keyword and its usage in TypeScript.