Skip to Content
2. Building with TypeScriptFunctions

Functions

By Nael Shiab

Last updated on

By encapsulating code within functions, you can reuse the same code over and over. Functions also help break up long scripts into modular chunks, making them easier to manage and debug.

I assume you’ve completed Chapter 1, especially the Setup lesson, before diving into this one.

Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Click here to get in touch.

Setup

Create a new, empty folder on your computer, open it with VS Code, and create a file named main.ts inside it.

Type this code in main.ts and save the file:

main.ts
console.log("Hello!");

Open the terminal (Command + J on Mac or Control + J on Windows) and run this command:

node --watch main.ts

This runs our code and automatically runs it again each time we save a change, so we can see the results as we work.

VS Code showing console.log("Hello!") in main.ts and Hello! in the terminal running node --watch main.ts.

Basic function

To create a function, you need to declare it using the function keyword, followed by its name with parentheses () and curly brackets {}.

Let’s create a function named sayHello that logs "Hello!". The code you want the function to execute must go between the {}. We’ll talk about what goes between the () in a minute.

Replace the contents of main.ts with the following code.

main.ts
function sayHello() { console.log("Hello!"); }

If you save and run this code, nothing will get logged. You created a function, but you haven’t called it yet.

To call a function, you need to use its name followed by (), as shown on line 5 below.

main.ts
function sayHello() { console.log("Hello!"); } sayHello()
💡

Give functions clear names, usually starting with a verb. By convention, function names use camel case: no spaces, the first word lowercase, and each following word starting with a capital letter, like sayHello.

VS Code showing sayHello() called on line 5 and Hello! logged in the terminal.

Now, you can reuse it as many times as you want!

main.ts
function sayHello() { console.log("Hello!"); } sayHello() sayHello() sayHello() sayHello() sayHello()

VS Code showing five calls to sayHello() and Hello! logged five times in the terminal.

Parameters

Our function is pretty basic. It would be more interesting if we could pass a name to it for a personalized greeting, like "Hello, Nael!"

To achieve this, we need to add a parameter to our function, something it can use.

Parameters are defined between the () when declaring the function, and they are typed.

In the code below, we add a parameter name to the function sayHello and specify that name must be of type string.

main.ts
function sayHello(name: string) { console.log("Hello, " + name + "!"); } sayHello();
💡

On line 1, the name: string syntax is called an explicit type. It means that name must be a string. Most of the time, the types in your code are inferred. But in some cases, you need to explicitly specify what you want the types to be. Defining function parameters is one of these cases.

When you use + with strings, it concatenates them, meaning it joins them together. But we usually prefer backticks with ${} to insert a variable’s value or the result of an expression into a string. Strings written with backticks are called template literals, and inserting values this way is called string interpolation.

Here’s the same function using string interpolation:

main.ts
function sayHello(name: string) { console.log(`Hello, ${name}!`); } sayHello();

VS Code reports a type error here: the function expects a name argument, but the call on line 5 provides none. In the terminal, you can see Hello, undefined! because we haven’t passed a name to the function.

VS Code reporting a missing name argument for sayHello(), with Hello, undefined! logged in the terminal.

Let’s pass the argument "Nael" to the function on line 5. The error disappears, and the function logs "Hello, Nael!" as expected.

main.ts
function sayHello(name: string) { console.log(`Hello, ${name}!`); } sayHello("Nael");

VS Code showing sayHello("Nael") without an error and Hello, Nael! in the terminal.

And now, we can call the same function with different names.

main.ts
function sayHello(name: string) { console.log(`Hello, ${name}!`); } sayHello("Nael"); sayHello("Emily"); sayHello("Diana"); sayHello("John"); sayHello("Jane");

VS Code showing sayHello() called with five different names and the corresponding greetings in the terminal.

If you pass a number instead of a string as name, VS Code reports a type error. main.ts turns red with a 1, indicating one error in the file. Hover over the number to see what’s wrong.

Again, types work for you. Type checking on function parameters will save you from many debugging sessions. 🐞

VS Code reporting that a number cannot be passed to the string parameter name, with main.ts marked red and one error.

Anything can be a function parameter: strings, numbers, booleans, objects, or even other functions!

You can also have multiple parameters between the function (), separated by a comma.

For example, here, we add a new parameter isTired, which is expected to be a boolean. When isTired is true, we add "You look tired...". If it’s false, we add "You look great!".

main.ts
function sayHello(name: string, isTired: boolean) { if (isTired) { console.log(`Hello, ${name}! You look tired...`); } else { console.log(`Hello, ${name}! You look great!`); } } sayHello("Nael", true); sayHello("Emily", false);

VS Code showing sayHello() with name and isTired parameters and different greetings for Nael and Emily.

Return

If you hover over the function (or start typing it), you’ll see the function signature, which indicates the types of its parameters and what it returns.

It shows function sayHello(name: string, isTired: boolean): void. The : void at the end indicates that the function does not return anything, which makes sense because we are just logging information to the terminal for now.

VS Code displaying the sayHello function signature with name and isTired parameters and a void return type.

However, in many cases, you want a function to return something.

For example, let’s say you’re Canadian and want to visit the Eiffel Tower. You could create a function to convert Canadian dollars to Euros. As of the time of writing this (2025-01-22), the conversion rate is 0.67.

main.ts
function convertDollarsToEuros(dollars: number) { return dollars * 0.67; } convertDollarsToEuros(100);

Here, the function uses the keyword return. If you hover over the function, you’ll see : number at the end, which means this function returns a number.

VS Code showing convertDollarsToEuros() and its inferred number return type.

But if you run the code, it looks like nothing happens!

Actually, the calculations are performed and returned, but returned to nowhere! You need to store the result somewhere or log it directly.

Let’s create a variable euros to store the returned value of convertDollarsToEuros(dollars) and log a proper message.

main.ts
function convertDollarsToEuros(dollars: number) { return dollars * 0.67; } const dollars = 100; const euros = convertDollarsToEuros(dollars); console.log(`${dollars} Canadian dollars is ${euros} euros`);

VS Code showing the dollars and euros variables and logging that 100 Canadian dollars is 67 euros.

As with parameters, returned values can be anything: strings, numbers, booleans, objects, or even functions.

Because functions are typed, the variables storing their return values are automatically typed as well.

If you hover over euros, you’ll see that its type is number because the return value of convertDollarsToEuros is number. When working on more complex algorithms with many functions, this type inference feels magical and helps you stay sane.

Hovering over euros in VS Code shows its inferred number type.

Exporting and importing

Since main.ts is our primary code entry point, we try to keep it lean. Cluttering it with function declarations is not optimal.

Typically, we keep functions in their own files. This makes debugging easier and also makes the functions reusable, as you can import them into other files.

We often group such functions into a folder called helpers.

In the Explorer in VS Code (the tab on the left):

  1. Right-click on your project folder and select New Folder. Name it helpers and press Enter.
  2. Right-click on helpers and select New File. Name it convertDollarsToEuros.ts and press Enter.
  3. Move the convertDollarsToEuros function declaration into this file.

Nothing will work for now, but that’s okay. We still need to export and import the function.

VS Code showing main.ts beside helpers/convertDollarsToEuros.ts, with a ReferenceError in the terminal.

💡

In VS Code, files are opened as tabs. By default, you see one file at a time. If you want to see multiple files side by side, right-click on a tab and then click Split up, Split down, Split left, or Split right. Try Split right to view your main file and helper side by side.

Now, the convertDollarsToEuros function is in a separate file, but it can’t be used anywhere else yet.

We need to make it available by exporting it.

Update your code in convertDollarsToEuros.ts by adding the keywords export default on line 1.

helpers/convertDollarsToEuros.ts
export default function convertDollarsToEuros(dollars: number) { return dollars * 0.67; }

Now that convertDollarsToEuros is exported, we can import it anywhere we want!

In our case, we want to use it in main.ts, so we need the import keyword, as shown below.

As you start typing, VS Code might suggest importing convertDollarsToEuros. If it does, this handy feature saves you typing everything and helps avoid typos. Press Enter to accept the suggestion and complete the import automatically.

main.ts
import convertDollarsToEuros from "./helpers/convertDollarsToEuros.ts"; const dollars = 100; const euros = convertDollarsToEuros(dollars); console.log(`${dollars} Canadian dollars is ${euros} euros`);

And now, everything works! If we had multiple files where convertDollarsToEuros was needed, we could easily import the function and reuse it in multiple places!

If the exchange rate changes, we only need to update it in this function. Every part of our code that calls it will then use the new rate. That’s another benefit of organizing code into small, reusable functions!

VS Code showing the exported helper function imported in main.ts and the conversion result in the terminal.

💡

When you import a file, you need to tell your computer where to find it with a path. Here, ./helpers/convertDollarsToEuros.ts is a relative path because it starts with ./. The . tells the computer to start where the current file is. In this case, since we are updating main.ts, it starts in the folder where main.ts is. Then /helpers tells the computer to go inside the helpers folder. Finally, /convertDollarsToEuros.ts tells it to import the content of this file.

Also, node --watch main.ts watches all of main.ts’s dependencies, including convertDollarsToEuros.ts and any other files containing functions, methods, or code that you import. If you update convertDollarsToEuros.ts and save it, the terminal will be cleared and the script will rerun too. So useful!

Change 0.67 to 0.65 to see it in action. Your script reruns and logs the updated result in the terminal.

Node detecting a change in convertDollarsToEuros.ts and rerunning main.ts to display 65 euros.

💡

You might think that creating multiple files makes it more difficult to navigate your code. But if you press CMD on Mac or CTRL on PC and click on a function in your code, VS Code will automatically take you to the function’s file by opening a new tab.

Documentation

Documenting your functions is crucial if you want to reuse them in the future. Comments can do a pretty good job, but there is something even more handy: JSDoc.

To create documentation with JSDoc syntax, you need to use /** at the beginning of the documentation and */ at the end. Each line should start with a *. And that’s it!

Here’s some basic documentation added at the beginning of convertDollarsToEuros.ts. We have a simple description at first, followed by a description of the parameter dollars, and finally a description of the returned value.

helpers/convertDollarsToEuros.ts
/** * Converts an amount in Canadian dollars to euros. * * @param dollars - The amount in dollars to be converted. * @returns The equivalent amount in euros. */ export default function convertDollarsToEuros(dollars: number) { return dollars * 0.65; }
💡

In this example, I’m being fancy with @param and @returns, but you can also write regular text inside the JSDoc comment. It will still appear as documentation when you hover over the function.

The reason why JSDoc is so handy is because VS Code (and many other tools) understands it. If you hover over the function in main.ts now, you’ll see not only the types but also your documentation popping up!

This is especially useful when functions call other functions: wherever you’re working, just hover over a function to read its documentation.

VS Code showing JSDoc comments for convertDollarsToEuros and their documentation when hovering over the function.

We can improve our documentation by adding an example.

To ensure that VS Code recognizes the example as code, we use a fenced code block with three backticks ```. When opening the block, we also specify ts so VS Code knows it’s TypeScript code and applies the relevant syntax highlighting.

helpers/convertDollarsToEuros.ts
/** * Converts an amount in Canadian dollars to euros. * * @example * ```ts * const dollars = 100; * const euros = convertDollarsToEuros(dollars); * console.log(euros); // 65 * ``` * * @param dollars - The amount in dollars to be converted. * @returns The equivalent amount in euros. */ export default function convertDollarsToEuros(dollars: number): number { return dollars * 0.65; }

VS Code showing a JSDoc example in the helper file and when hovering over the imported function.

Arrow functions

Sometimes, you just need a simple function, especially when passing functions as parameters in methods like those for arrays.

Arrow functions provide a shorter way to write functions.

For example, this is a regular function that logs a string.

function sayHello(name: string) { console.log(`Hello, ${name}!`); } sayHello("Nael") // "Hello, Nael!"

It could be rewritten as an arrow function like this. It’s called an arrow function because the => resembles an arrow.

const sayHello = (name: string) => console.log(`Hello, ${name}!`); sayHello("Nael") // "Hello, Nael!"

In the example above, there is no significant benefit to using an arrow function. However, when working with array methods, arrow functions can make your code simpler and more readable.

In the code below, we have an array of numbers that we want to filter, keeping only the positive numbers. The .filter() method requires a function as a parameter, so we declare the isPositive function and pass it to .filter().

Here’s how it looks with a regular function.

const numbers = [-2, -1, 0, 1, 2]; function isPositive(num: number) { return num > 0; } const positiveNumbers = numbers.filter(isPositive); console.log(positiveNumbers); // [1, 2]

But we could simplify all of this by using an arrow function directly inside the .filter() parentheses.

const numbers = [-2, -1, 0, 1, 2]; const positiveNumbers = numbers.filter((num) => num > 0); console.log(positiveNumbers); // [1, 2]

Because the type of numbers is inferred as a number[], your computer infers that the arrow function parameter num can only be a number. It’s very convenient.

With the regular function, you had to explicitly type num: number because your computer had no way of knowing for sure what num was supposed to be.

Conclusion

Functions are a fundamental part of programming. They help you organize your code, make it reusable, and keep it clean.

If you want to dig deeper into functions, check out the Refactoring lesson in the Extras chapter.

Enjoyed this? Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Get in touch if you have any questions.