Start learning free

LESSON 29 OF 348 · FUNCTIONS I

Functions in TypeScript: Declaring and Calling

Lesson Read the full explanation

A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in TypeScript:

function functionName() {
	// function body (where all the instructions are written)
}

There are two main components of a function:

1. The function header:

It consists of:

  • function keyword which tells TypeScript that we are about to define a function
  • functionName is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons


2. The function body:

This is the code that TypeScript executes whenever the function is called.

It consists of one or more TypeScript statements placed inside curly brackets {} (where we have our TypeScript comment).

Here's an example of a function:

function sayHello() {
	console.log("Hello World");
}

Notice that we indented (added one tab before) our console.log("Hello World");.

Indentation is not mandatory like in Python, but we use it to make our code easier to read.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

// Function declaration:
function sayHello() {
	console.log("Hello World");
}
	
// Function call:
sayHello(); // Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the dev console.

We can call a function as many times as it is needed.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · FUNCTIONS I

    Functions in TypeScript, explained

    What a function is

    A function is a named container for a few lines of code that perform one task. Instead of writing everything in one long block, you split the program into small pieces, each with a name that says what it does. A function can then be run as many times as you need by using that name.

    A function declaration in TypeScript looks like this:

    function functionName() {
        // function body: the instructions go here
    }
    

    It has two parts.

    The header

    • The function keyword tells TypeScript that a function definition follows.
    • functionName is the name, an identifier you use to refer to the function. Names are case-sensitive, so sayHello and sayhello are different functions.
    • The parentheses () hold the function's inputs. They are empty for now and are explained in later lessons.

    The body

    The body is the code that runs when the function is called. It is a sequence of statements between curly braces {}:

    function sayHello() {
        console.log("Hello World");
    }
    

    The line inside is indented to show that it belongs to the function. TypeScript doesn't require indentation, unlike Python, where it is part of the syntax. The curly braces mark where the body begins and ends, and indentation is just there to help human readers.

    Declaring is not calling

    If you run the function above on its own, nothing is printed. A declaration only tells TypeScript that the function exists. The body runs when you call the function, by writing its name followed by parentheses:

    function sayHello() {
        console.log("Hello World");
    }
    
    sayHello(); // Hello World
    sayHello(); // Hello World
    

    Every call runs the whole body again from the top, so two calls print the message twice. Forgetting the parentheses is a classic mistake: writing sayHello; refers to the function without running it, and nothing happens.

    The return type

    TypeScript lets you state what a function gives back. A function that only prints and returns nothing is annotated with : void, written after the parentheses:

    function sayHello(): void {
        console.log("Hello World");
    }
    

    The annotation is for the compiler and for readers. It is removed when the code is compiled to JavaScript. Without it, TypeScript works out the type itself, and in this case it would infer void anyway. At run time a function that returns nothing hands back undefined, so console.log(sayHello()) prints the greeting and then undefined.

    The lesson's exercise

    The task is to write a function named sayHello that prints Hello everybody!, and to call it. There are three steps:

    1. Declare the function at the top of the file, with the name sayHello and the void return type, because it prints a message and doesn't return a value.
    2. Put the print statement in the body so every call shows the greeting. Statements end with a semicolon.
    3. Call sayHello() below the function. Without this line the program would print nothing.
    function sayHello(): void {
        console.log("Hello everybody!");
    }
    
    sayHello();
    

    This prints Hello everybody! once. A second sayHello(); line would print it twice.

    Gotchas

    • Missing braces. The body must be wrapped in { }. A header with no body, followed by a separate statement, makes the compiler report an error, and the function is not defined in the JavaScript it writes.
    • Calling before declaring. Function declarations are hoisted, so a call written above the declaration still works in the same file. Even so, defining functions before using them is easier to read.
    • Different names. The name in the call has to match the name in the declaration exactly, including capitals.

    Key takeaways

    • A function groups statements under a name.
    • The header is function, a name and parentheses; the body is in curly braces.
    • Declaring a function does not run it; calling it with name() does.
    • A function can be called as many times as needed.
    • : void says that the function returns nothing.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free