WHAT'S NEW
TypeScript · Lesson 03 of 11

Functions in TypeScript

Write code once and use it again! Learn how TypeScript functions accept information, perform tasks, and return results — with types that help prevent mistakes.

Functions Parameters Return Types Reusable Code
● ● ●   functions.ts
function greet(name: string)
  : string {
  return `Hello, ${name}!`;
}

console.log(
  greet("Alex")
);
CONSOLE OUTPUT
> Ready to run…
01 / Meet Functions

Write It Once, Use It Again

Imagine building a website that welcomes every visitor. You could write a separate greeting for each person, but that would quickly become repetitive.

A function lets you group instructions under a name and run those instructions whenever you need them.

hello.ts
function sayHello(): void {
  console.log("Hello from mC0de!");
}

sayHello();
sayHello();
Console Output:
Hello from mC0de! Hello from mC0de!

The function’s instructions are written once but executed twice. Calling sayHello() tells TypeScript to run the instructions inside its braces.

Remember: Defining a function doesn’t automatically run its instructions. You must call it, unless another part of your program calls it for you.
02 / Function Parameters

Give Your Function Information

Functions become more useful when they can work with different values. A parameter is a named input declared in a function. An argument is the actual value you pass when calling it.

parameters.ts
function greet(name: string): void {
  console.log("Hello, " + name + "!");
}

greet("Alex");
greet("Jordan");
Console Output:
Hello, Alex! Hello, Jordan!

The parameter name: string tells TypeScript that the function expects text. The values "Alex" and "Jordan" are arguments.

A type mismatch
greet(42); // Type error: number is not string

TypeScript can detect that mismatch before the function executes.

03 / Multiple Parameters

Accept More Than One Value

A function can accept multiple parameters, separated by commas. Each parameter can have its own type.

multiple-parameters.ts
function showPlayer(
  name: string,
  score: number
): void {
  console.log(name + " scored " + score);
}

showPlayer("Alex", 100);
showPlayer("Jordan", 85);
Console Output:
Alex scored 100 Jordan scored 85

The order of arguments matters. TypeScript checks each argument against the corresponding parameter.

Quick check: Would showPlayer(100, "Alex") work? No — the first parameter expects a string and the second expects a number.
04 / Return Values

Let Your Function Give Something Back

Some functions simply perform an action. Others calculate or create a value and return it to the code that called them.

return-values.ts
function add(
  first: number,
  second: number
): number {
  return first + second;
}

const total: number = add(10, 5);

console.log(total);
Console Output:
15

The : number after the parentheses describes the function’s return type. The return statement sends the calculated value back to the caller.

TypeScript can also infer return types, but writing them explicitly is often useful when learning or documenting a function’s intended behavior.

05 / Understanding Void

Not Every Function Returns a Result

When a function doesn’t return a meaningful value, you can describe its return type as void.

void-functions.ts
function announce(message: string): void {
  console.log("Announcement: " + message);
}

announce("Welcome to TypeScript!");
Console Output:
Announcement: Welcome to TypeScript!

Printing to the console is an action, not the same as returning a value. Compare console.log(message), which displays information, with return message, which sends information back to the caller.

06 / Arrow Functions

A Shorter Way to Write Functions

TypeScript also supports arrow functions, which use the => symbol. They’re common in modern JavaScript and TypeScript.

arrow-functions.ts
const double = (value: number): number => {
  return value * 2;
};

console.log(double(5));
Console Output:
10

For a short expression, an arrow function can use an implicit return:

Short arrow function
const triple = (value: number): number =>
  value * 3;

console.log(triple(4)); // 12
Good to know: Arrow functions and regular functions aren’t identical in every situation. For example, they handle this differently. We’ll revisit that when learning about classes.
07 / Optional and Default Parameters

Make Functions More Flexible

Sometimes an argument should be optional. Add ? after a parameter name to indicate that callers may omit it.

optional-parameters.ts
function welcome(name?: string): void {
  if (name) {
    console.log("Welcome, " + name + "!");
  } else {
    console.log("Welcome, developer!");
  }
}

welcome("Alex");
welcome();
Console Output:
Welcome, Alex! Welcome, developer!

An optional parameter may be undefined, so your function should account for the missing value.

Alternatively, provide a default value:

default-parameters.ts
function greet(
  name: string = "developer"
): string {
  return "Hello, " + name + "!";
}

console.log(greet());
console.log(greet("Alex"));
Console Output:
Hello, developer! Hello, Alex!
08 / Catching Function Type Errors

Protect Your Function’s Inputs and Outputs

TypeScript doesn’t just check variables. It also checks function arguments and returned values.

return-type-error.ts
function getScore(): number {
  return "one hundred"; // Type error!
}

This function promises to return a number but actually returns a string. TypeScript reports the conflict.

Corrected function
function getScore(): number {
  return 100;
}

console.log(getScore()); // 100
Remember: Parameter types protect what goes into a function. Return types describe what should come out.
09 / Putting It Together

Build a Reusable Greeting Generator

Let’s combine typed parameters, return values, and function calls into a useful example.

greeting-generator.ts
function createGreeting(
  name: string,
  language: string
): string {
  return `Hello, ${name}! Enjoy learning ${language}!`;
}

const greeting = createGreeting(
  "Alex",
  "TypeScript"
);

console.log(greeting);
Console Output:
Hello, Alex! Enjoy learning TypeScript!

One function can create greetings for any developer and any programming language. You simply provide different arguments.

🚀 mC0de Challenge

Create a Personalized Greeting Generator

Build a reusable TypeScript function that welcomes developers and celebrates their progress.

Your Mission

  1. Change the name and programming language passed to createGreeting().
  2. Update the function’s returned message to include your own greeting.
  3. Change the lessonsCompleted argument to a different number.
  4. Use console.log() to display the returned greeting.
  5. Call the function again with another developer’s details.
  6. Run the code and verify both greetings appear.
Extra challenge: Pass a string instead of a number for lessonsCompleted. Read the TypeScript error, then correct the argument and run the code again.
💻 Interactive TypeScript Sandbox

Make Your Functions Come Alive!

Edit the function, customize its arguments, and run your code. The sandbox checks TypeScript types, compiles the program, and displays console output.

Console Output
Lesson 03 Recap

What You’ve Learned

You’re Building Reusable TypeScript Code!

You can now:

  • Declare and call TypeScript functions.
  • Distinguish parameters from arguments.
  • Add types to function parameters.
  • Return values using return.
  • Describe return types with string, number, or void.
  • Write arrow functions.
  • Use optional and default parameters.
  • Recognize and correct function type errors.

Next up: Loops — learn how to repeat instructions efficiently using for, while, and other looping techniques!

Your Learning Journey

0 / 11 Completed

Keep going! Every completed lesson brings you closer to building reliable applications with TypeScript.

🎉

Fantastic Work!

You’ve learned how to create reusable TypeScript functions, work with typed parameters, return values, and write arrow functions. You’re building the skills to organize code into clear, dependable pieces!

PIX0
</> {} JS 01
0101 </> CSS JS HTML PIX0 const {} 1010 async mC0de function return 0101 <div> 1010 PIX0 CSS JS HTML const {} 0101 mC0de
PIX0 // WORLD OF CODE
PIX0 IS PREPARING SOMETHING AWESOME FOR YOU 0%