Start learning free

LESSON 39 OF 348 · FUNCTIONS I

Function Parameters and Arguments in TypeScript

Lesson Read the full explanation

So far, the functions we've created execute a fixed task without context / inputs. But most often we want our functions to produce different outcomes depending on the context behind the function call.

For example, it would be nice if sayHello() would print a personalized message such as "Hello humans" or "Hello cats" or "Hello dogs", depending on the audience instead of "Hello world" no matter what.


Function parameters:

Function parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

When a function is defined, its parameters are specified between the parentheses that follow the function name.

Here is our function with one parameter, audience:

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

Calling with arguments:

Then we can call sayHello() and specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments.

// Function declaration:
function sayHello(audience) {
  console.log("Hello " + audience);
}

//Function call:
sayHello("humans"); // Output: Hello humans

We have passed one string argument: "humans". Inside the function audience will equal string "humans" and acts just like a regular variable.


Multiple parameters:

A function can have as many parameters as it needs. Here is a function with two parameters:

Here is a function with two parameters:

function sayHello(name, age) {
  console.log(name + ", aged " + age);
}

// Let's call it:
sayHello("John", 30); // Output: John, aged 30
sayHello("Mary", 26); // Output: Mary, aged 26

Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.


Variables as arguments:

Variables can also be passed as arguments for function calls:

function sayHello(name, age) {
  console.log(name + ", aged " + age);
}

let name = "Andy";
let age = 28;

sayHello(name, age); // Output: Andy, aged 28

sayHello("Mary", age); // Output: Mary, aged 28

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

    Function Parameters And Arguments in TypeScript, explained

    Why functions need inputs

    A function that always does the same fixed thing is limited. A function that prints a greeting is more useful if the greeting can change: "Hello humans" for one caller, "Hello cats" for another. To make that possible, a function accepts inputs. The function's definition declares them as parameters, and each call supplies the actual values, called arguments.

    Parameters

    A parameter is a placeholder written between the parentheses of the definition. In TypeScript, you also write its type after a colon:

    function sayHello(audience: string): void {
        console.log("Hello " + audience);
    }
    

    Here audience is a parameter of type string. Inside the body it behaves like a variable that already has a value when the function starts. The : void at the end says the function returns nothing.

    Arguments

    An argument is the value you write in the parentheses of a call:

    sayHello("humans");
    sayHello("cats");
    

    This prints:

    Hello humans
    Hello cats
    

    In the first call the argument "humans" is stored in audience, so the body prints Hello humans. In the second call audience holds "cats". Each call gets its own value.

    To keep the terms apart: the parameter is the name in the definition, the argument is the value in the call.

    Several parameters

    A function can have as many parameters as it needs, separated by commas, each with its own type:

    function describe(person: string, age: number): void {
        console.log(person + ", aged " + age);
    }
    
    describe("John", 30);
    describe("Mary", 26);
    

    Output:

    John, aged 30
    Mary, aged 26
    

    Arguments are matched to parameters by position: the first argument goes to the first parameter, the second to the second. Swapping the order of the arguments swaps what each parameter receives.

    Types are checked by the compiler, not at run time

    The annotation name: string tells TypeScript what callers must pass. The compiler checks every call against it, and reports an error for a call with the wrong number of arguments or the wrong type, for example a missing argument (Expected 1 arguments, but got 0) or a number where a string is expected.

    The annotation is erased when TypeScript compiles to JavaScript. It checks nothing while the program runs and converts nothing. The JavaScript still runs even when the compiler reports an error, and a cast such as as any silences the check. The function simply runs with whatever it receives: calling welcomeUser(5 as any) on the function below prints Welcome, 5!, and a call with no argument prints Welcome, undefined!.

    The lesson's exercise

    The exercise has five steps:

    1. Define the function. Write function welcomeUser(name: string): void. The parameter is called name and takes a string.
    2. Print the greeting. In the body, join "Welcome, ", name and "!" with +. For "Andy", the text is Welcome, Andy!. Mind the space after the comma.
    3. Call it with a literal. After the definition, write welcomeUser("Andy");. The string is the argument, and the parameter name receives it.
    4. Create a variable. Declare let name: string = "John";. The annotation is optional, since TypeScript infers string from the value.
    5. Call it with the variable. Write welcomeUser(name);. The function receives the value stored in the variable, "John".

    The complete program:

    function welcomeUser(name: string): void {
        console.log("Welcome, " + name + "!");
    }
    
    welcomeUser("Andy");
    let name: string = "John";
    welcomeUser(name);
    

    It prints:

    Welcome, Andy!
    Welcome, John!
    

    Variables as arguments

    You can pass a variable instead of a literal. The call uses the variable's current value, and the function never sees the variable itself. A parameter is a separate variable that exists only during the call. Here the top-level variable and the parameter are both called name, but they are two different variables that happen to share a name. Reassigning the parameter inside a function does not change the caller's variable.

    Common mistakes

    • Wrong order of arguments. With describe(30, "John") the compiler complains about types here, but if two parameters have the same type, the swap goes unnoticed and the output is wrong.
    • Missing or extra arguments. TypeScript requires exactly as many arguments as there are parameters (unless a parameter is optional or has a default).
    • Forgetting the space. "Welcome," without the trailing space prints Welcome,Andy!.
    • Putting quotes around a variable. welcomeUser("name") passes the text name, not the variable's value.

    Key takeaways

    • Parameters are declared in the definition; arguments are supplied in the call.
    • Arguments match parameters by position.
    • A parameter's type annotation is checked while compiling and erased afterwards.
    • A variable passed as an argument gives the function its value, not the variable.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free