So far, we've learned that functions are like mini-programs that perform specific tasks. But how do we give these functions the information they need to do their job, and how do they communicate the results back to us? This is where parameters and return values come in. Think of parameters as the ingredients you hand to your chef (the function), and the return value as the delicious dish they present back to you.
Parameters: The Inputs to Your Functions
Parameters are variables that are declared within the parentheses of a function's definition. They act as placeholders for the data that the function expects to receive when it's called. When you call a function, you provide actual values, called arguments, which are then assigned to these parameters.
function greet(name) {
console.log('Hello, ' + name + '!');
}In the example above, name is a parameter. When we call greet('Alice'), the string 'Alice' becomes the argument for the name parameter. The function then uses this value inside its body.
greet('Alice'); // Output: Hello, Alice!
greet('Bob'); // Output: Hello, Bob!Functions can have multiple parameters, separated by commas. This allows them to receive more complex information.
function add(num1, num2) {
let sum = num1 + num2;
console.log(sum);
}add(5, 3); // Output: 8
add(10, 20); // Output: 30Return Values: The Outputs of Your Functions
While some functions might just perform an action (like printing to the console), many need to calculate something and give that result back to the part of the program that called them. This is where the return statement comes into play. A return statement specifies the value that a function will send back. Once a return statement is executed, the function stops running.