TypeScript Variables let and const

In TypeScript, variable declaration follows a similar pattern to JavaScript and utilizes the var, let, and const keywords. Below is an example demonstrating how to declare variables using these two specific keywords:

let myNumber: number = 42;
const myString: string = "Hello, world!";

In this example, we use the let keyword to declare a variable named myNumber, initializing it with the numeric value 42. We also utilize the const keyword to declare a constant named myString, initialized with the string literal "Hello, world!". Note that when declaring the myNumber variable, we included a type annotation specifying its type as number. This enables TypeScript to perform compile-time error checking and provides improved code completion suggestions.

Additionally, it is important to note that variables declared with const must be initialized at the time of declaration and cannot be reassigned afterward. However, if a const variable refers to an object or array, its properties or elements can still be modified. For instance:

const myArray: number[] = [1, 2, 3];
myArray.push(4); // This is valid; it appends 4 to the end of the array
myArray[0] = 0; // This is also valid; it changes the first element to 0

In this example, we declare a constant named myArray initialized with an array containing three numbers. Although myArray itself cannot be reassigned (e.g., pointing to a different array), its contents remain mutable. We can add new elements to the end of the array or modify existing values within it.