Parameters and Arguments

Our functions so far do exactly the same thing every time they are called. But to calculate the area of any rectangle, the function needs to know its width and height. Functions get such values through parameters:

function introduce(name) {
    console.log(`My name is ${name}.`);
}

introduce("Anna");
introduce("Tom");

This prints:

My name is Anna.
My name is Tom.

In the definition, name in the parentheses is a parameter: a variable that the function can use in its body. You don't create it with let; the parentheses in the definition create it. In the call, the value in the parentheses, "Anna", is an argument. When you call the function, the argument is stored in the parameter, and then the body runs. On the first call, name is "Anna", on the second call it's "Tom".

These two words are easy to mix up, so remember: a parameter is the name in the definition, an argument is the value in the call.

A function can have several parameters, separated by commas. The arguments then go into the parameters in order: the first argument into the first parameter, the second into the second, and so on:

function introduce(name, age) {
    console.log(`My name is ${name} and I am ${age} years old.`);
}

introduce("Anna", 21);
introduce(21, "Anna");

This prints:

My name is Anna and I am 21 years old.
My name is 21 and I am Anna years old.

In the second call, the arguments are swapped, so 21 went into name and "Anna" into age. JavaScript doesn't care what the values mean, only what order they come in.

Now we can solve the problem from the beginning of the lesson: one function that prints the area of any rectangle.

Instructions

Create a function printArea with two parameters, width and height. In its body, print width * height.

Below the function, call it with the arguments 5 and 6. The program prints 30.

Call printArea two more times, for the other two rectangles from the beginning of the lesson: with the arguments 10 and 5, and then 1 and 5. The program then prints 30, 50 and 5, just like the long code at the beginning, but now each rectangle takes a single line.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

3/10

Next