0
0
Typescriptprogramming~3 mins

Why Declaring functions and classes in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write instructions once and use them everywhere without mistakes?

The Scenario

Imagine you need to repeat the same set of instructions many times in your code, like calculating a total price or creating a user profile. Without functions or classes, you'd have to write the same lines over and over again everywhere.

The Problem

Writing the same code repeatedly is slow and tiring. It's easy to make mistakes or forget to update all copies when something changes. Managing complex data without classes can become confusing and messy.

The Solution

Functions let you write a set of instructions once and reuse them anytime, making your code cleaner and easier to fix. Classes help you organize related data and actions together, like a blueprint for creating many similar objects.

Before vs After
Before
let price1 = 10; let price2 = 20; let total = price1 + price2; // repeated everywhere
After
function sum(a: number, b: number): number { return a + b; } let total = sum(10, 20);
What It Enables

It lets you build clear, reusable, and organized code that's easy to maintain and expand.

Real Life Example

Think of a class as a recipe for making many cakes. Instead of writing the recipe each time, you just follow the class blueprint to create each cake (object) with its own flavor and size.

Key Takeaways

Functions save time by reusing code.

Classes organize data and behavior together.

Both make your code easier to read and maintain.