Function Parameters
So far, we have only created functions without inputs. With parameters, however, we can provide the function with different inputs, thereby affecting its behavior.
We specify parameters in parentheses after the function name during its definition, and in the function body, we use them as normal variables. For example:
function greet(name) {
console.log("Hello, " + name);
}
greet("Carl"); // Prints: Hello, Carl
greet("Jane"); // Prints: Hello, Jane
This function has one parameter: name
. When we call the function using greet("Carl")
, we assign the value "Carl"
to the parameter name
, which we then print using the console.log
command. Similarly for greet("Jane")
.
A function can also have multiple parameters. Let's look at an example:
function multiply(a, b) {
const result = a * b;
console.log(result);
}
multiply(2, 3); // Prints: 6
multiply(5, 10); // Prints: 50
This code defines a function multiply
with two parameters a
and b
. The function calculates and prints their product. It's important to realize that the order in which we write the parameters in the function definition is the same order we use when calling the function. Simply put, with multiply(2, 3)
, 2
is assigned to a
and 3
is assigned to b
.
Instructions
Create a function named sum
that has two parameters x
and y
. The function will print the sum of these two arguments.
Call this function with parameter values 3
and 4
.
Call the function sum
again with parameter values 10
and 15
.
Start programming for free
4/7