TypeScript:
Organizing code into functions

How to:

Imagine you’re making a basic calculator. Instead of writing the addition logic everywhere you need it, create an add function:

function add(x: number, y: number): number {
  return x + y;
}

console.log(add(5, 7)); // Sample output: 12

Now, let’s say we need a function to multiply:

function multiply(x: number, y: number): number {
  return x * y;
}

console.log(multiply(3, 4)); // Sample output: 12

Notice how we focus on one task per function? That’s the heart of organizing code.

Deep Dive

Historically, as programming languages evolved, functions became vital in structuring code, drawing from mathematical functions. They’re a staple in procedural programming and live on in object-oriented and functional programming paradigms.

Alternatives? You could just not use functions, but that’s a one-way ticket to Spaghetti Town. Or you could go OOP (Object-Oriented Programming) and pack functionality into methods—which are basically functions that belong to objects.

Implementation-wise, TypeScript insists on types. Defining input and output types for functions isn’t just good manners; it’s a must for clean TypeScript code. Plus, with TypeScript, you get nifty features like overloads, generics, and optional parameters to supercharge your functions.

See Also

Check out these resources to level up your function game: