Search⌘ K
AI Features

The let and const Keywords

Explore the use of let and const keywords in TypeScript to manage variable scope effectively. Understand how let prevents variable redeclaration issues within code blocks and how const enforces immutability. This lesson helps you write clearer, more reliable TypeScript code by properly declaring variables.

We'll cover the following...

The let keyword

The fluid nature of JavaScript variables can sometimes cause errors when we inadvertently define variables with the same name but in a different scope within a code block.

Consider the following TypeScript code:

TypeScript 4.9.5
// Declare a variable called index with a type of number and assign it the value 0
var index: number = 0;
// If index is equal to 0, create a new block scope with a new variable also called index, but with a type of number and value of 2, and log its value
if (index == 0) {
var index: number = 2;
console.log(`index = ${index}`);
}
// Log the value of index
console.log(`index = ${index}`);
Variable index redeclared in the if-block
  • On line 2, we define a variable named index of type number using the var keyword and assign it a value of 0.

  • We then test if this value is equal to 0 on line 5, and if it is, we enter a code block.

  • The first statement in this code block on line 6 defines a variable named index of type number and ...