Start learning free

LESSON 37 OF 348 · FUNCTIONS I

Why Functions in TypeScript

Lesson Read the full explanation

Now that we've learned about functions, let's see why they are so important in our prgrammers' life:

Consider this: A student named Andy made a mistake and so his teacher told him to write this text 3 times on the whiteboard:

This is Andy
Andy made a mistake
Andy suffers the consequences

We would put this in a simple program like this:

console.log("This is Andy");
console.log("Andy made a mistake");
console.log("Andy suffers the consequences");

console.log("This is Andy");
console.log("Andy made a mistake");
console.log("Andy suffers the consequences");

console.log("This is Andy");
console.log("Andy made a mistake");
console.log("Andy suffers the consequences");

That's manageable. But what if the text consisted of more than 3 lines? And what if the teacher asked Andy to print it for 10 times or 100 times?

You can imagine that our code would get super long while executing 3 different instructions overall.


The story with functions:

This is where functions shine. We can write a function that prints the desired text and then just call the function for as many times as the teacher asks to:

function printMessage() {
	console.log("This is Andy");
	console.log("Andy made a mistake");
	console.log("Andy suffers the consequences");
}

printMessage();
printMessage();
printMessage();

Changing the story:

Need to print the text 3 more times? We call the function 3 more times instead of adding 9 lines to our program.

Need to change the student's name to Mike? We only change it inside the function instead of changing it in the whole program.

function printMessage() {
	console.log("This is Mike");
	console.log("Mike made a mistake");
	console.log("Mike suffers the consequences");
}

printMessage();
printMessage();
printMessage();
printMessage();
printMessage();

Note:

If you still don't like this code, especially the fact that we have 5 duplicate lines of code: printMessage(), you are correct! We will learn how we can make this even better with loops!


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · FUNCTIONS I

    Why Functions in TypeScript, explained

    The problem: repeated code

    Suppose a teacher asks a student to write the same three lines on the whiteboard three times. As a program, the direct version repeats every line:

    console.log("This is Andy");
    console.log("Andy made a mistake");
    console.log("Andy suffers the consequences");
    
    console.log("This is Andy");
    console.log("Andy made a mistake");
    console.log("Andy suffers the consequences");
    
    console.log("This is Andy");
    console.log("Andy made a mistake");
    console.log("Andy suffers the consequences");
    

    Nine lines for three repetitions is manageable. But ask for 100 repetitions, or for ten lines of text instead of three, and the file becomes huge. Worse, every change has to be made in every copy. If the name must change, you edit each copy, and missing one leaves a program that disagrees with itself.

    The solution: a function

    A function is a named block of code that you write once and run whenever you want. In TypeScript you define it with the function keyword, a name, parentheses and a body in braces:

    function printMessage(): void {
        console.log("This is Andy");
        console.log("Andy made a mistake");
        console.log("Andy suffers the consequences");
    }
    
    printMessage();
    printMessage();
    printMessage();
    

    The three calls print the same nine lines as before. The code that does the work now exists in one place.

    Two ideas matter here:

    • Defining is not running. The definition only teaches the program what printMessage means. The body runs each time you call the function by writing its name followed by parentheses.
    • Calling repeats the body. Each call runs the whole body from the start. Three calls give three runs.

    The return type void

    The : void after the parentheses is a TypeScript annotation. It says the function does not return a useful value; it only has an effect, here printing. The annotation helps the compiler catch mistakes, but it is erased when the code is compiled to JavaScript, so it changes nothing at run time. You can leave it out and TypeScript works out the type itself, but writing it makes the intent clear.

    Changing the story

    With the function, changes are cheap. To print the text twice more, add two calls instead of six lines. To change the student from Andy to Mike, edit the three lines inside the function, and every call picks up the change:

    function printMessage(): void {
        console.log("This is Mike");
        console.log("Mike made a mistake");
        console.log("Mike suffers the consequences");
    }
    
    printMessage();
    printMessage();
    printMessage();
    printMessage();
    printMessage();
    

    The repeated printMessage(); lines are still a little awkward. Loops, which come later, remove that repetition too.

    The lesson's exercise

    The exercise gives you a starter file with three comments and one line already written:

    // Function goes here:
    
    
    // Introduce yourself the first time:
    
    
    console.log("Sorry, I didn't hear you");
    
    // Introduce yourself again:
    

    You build the program in five steps:

    1. Define the function. Under the first comment, write function introduceYourself(): void { }. At this point, nothing runs.
    2. Print the first line. Inside the braces, print "My name is Andy" with console.log.
    3. Print the second line. On the next line, still inside the braces, print "I code in Python".
    4. Call it the first time. Under the second comment, write introduceYourself();. The semicolon ends the statement. Both lines are printed here.
    5. Call it again. Under the last comment, which is after the "Sorry, I didn't hear you" line, write the same call. Both lines are printed again without being typed again.

    The finished program:

    // Function goes here:
    function introduceYourself(): void {
        console.log("My name is Andy");
        console.log("I code in Python");
    }
    
    // Introduce yourself the first time:
    introduceYourself();
    
    console.log("Sorry, I didn't hear you");
    
    // Introduce yourself again:
    introduceYourself();
    

    Its output is:

    My name is Andy
    I code in Python
    Sorry, I didn't hear you
    My name is Andy
    I code in Python
    

    Common mistakes

    • Defining the function but never calling it. The program then prints only the "Sorry" line.
    • Leaving out the parentheses in the call. Writing introduceYourself; only mentions the function. It does not run it.
    • Putting a print outside the braces. A line after the closing brace is not part of the function and runs on its own, once, at that point in the file.
    • Misspelling the name. Names are case-sensitive, so introduceyourself() is not introduceYourself(), and the compiler reports that it cannot find the name.

    Key takeaways

    • A function names a block of code so you can write it once and run it many times.
    • Defining a function does not run it; a call, with parentheses, does.
    • Changing the function body changes the behaviour of every call.
    • The void return type marks a function that only performs an action.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free