TypeScript - let & const: A Beginner's Guide

Hello there, future coding superstar! Today, we're going to dive into the exciting world of TypeScript and explore two fundamental concepts: let and const. Don't worry if you've never written a line of code before – I'll be your friendly guide through this adventure.

TypeScript - let & const

Understanding Variables: The Building Blocks of Programming

Before we jump into let and const, let's talk about variables. Imagine you're planning a birthday party. You need to keep track of things like the number of guests, the cake flavor, and the party theme. In programming, we use variables to store and manage this kind of information.

Variables are like labeled boxes where we can put different types of data. We can change what's inside these boxes (the value of the variable) as our program runs.

Now, let's explore how TypeScript gives us two special ways to create these boxes: let and const.

Declaring a Variable Using the let Keyword

What is let?

The let keyword is used to declare variables that can be reassigned later in your code. It's like a reusable container that can hold different values over time.

How to Use let

Let's look at some examples:

let age = 25;
console.log(age); // Output: 25

age = 26;
console.log(age); // Output: 26

let name = "Alice";
console.log(name); // Output: Alice

name = "Bob";
console.log(name); // Output: Bob

In this example, we first declare a variable age and set it to 25. Later, we change it to 26. Similarly, we declare name as "Alice" and then change it to "Bob". The let keyword allows us to reassign these variables.

Block Scope

One important feature of let is block scoping. This means that a variable declared with let is only accessible within the block it's declared in. A block is typically defined by curly braces {}.

if (true) {
    let secretCode = 1234;
    console.log(secretCode); // Output: 1234
}
console.log(secretCode); // Error: secretCode is not defined

In this example, secretCode is only accessible inside the if block. Trying to use it outside results in an error.

Declaring a Variable Using the const Keyword

What is const?

The const keyword is used to declare variables that cannot be reassigned after they are initialized. Think of it as a sealed box – once you put something in, you can't change it.

How to Use const

Let's look at some examples:

const PI = 3.14159;
console.log(PI); // Output: 3.14159

PI = 3.14; // Error: Cannot assign to 'PI' because it is a constant.

const DAYS_IN_WEEK = 7;
console.log(DAYS_IN_WEEK); // Output: 7

In these examples, we declare constants for PI and the number of days in a week. If we try to reassign a new value to PI, TypeScript will throw an error.

const with Objects and Arrays

It's important to note that while const prevents reassignment, it doesn't make the value itself immutable. This is particularly relevant for objects and arrays:

const person = {
    name: "Charlie",
    age: 30
};

person.age = 31; // This is allowed
console.log(person); // Output: { name: "Charlie", age: 31 }

person = { name: "David", age: 25 }; // Error: Cannot assign to 'person' because it is a constant.

In this example, we can modify properties of the person object, but we can't reassign person to a completely new object.

When to Use let vs const

Here's a quick guide on when to use each:

Keyword Use Case
let When you need to reassign the variable later
For loop counters
When the value might change based on conditions
const For values that should not be reassigned
For declaring constants (like PI)
For object and array references that won't be reassigned

Best Practices and Tips

  1. Default to const: Start by using const for all your variables. Only switch to let if you find you need to reassign the variable.

  2. Descriptive Names: Use clear, descriptive names for your variables. For example, userAge is better than just a.

  3. Capitalize Constants: For true constants (like PI), use all uppercase names with underscores: const MAX_ARRAY_LENGTH = 100;.

  4. Be Consistent: If you're working on a team, follow the team's conventions for using let and const.

Conclusion

Congratulations! You've just taken your first steps into the world of TypeScript variables. Remember, let is your flexible friend that allows reassignment, while const is your steadfast companion for values that shouldn't change.

As you continue your coding journey, you'll find yourself using these keywords all the time. Don't worry if it feels a bit confusing at first – with practice, it'll become second nature.

Keep coding, stay curious, and remember: every expert was once a beginner. Happy TypeScripting!

Credits: Image by storyset