Parameters and Return Values in Functions
Functions are powerful blocks of reusable code, and their true utility often comes from their ability to accept inputs (parameters) and produce outputs (return values). Understanding how to effectively use parameters and return values is essential for writing flexible and modular JavaScript.
1. Parameters (Inputs)
Parameters are placeholders for values that you pass into a function when you call it. They are listed in the function's definition. When you call the function, the actual values you pass are called arguments.
Syntax
function functionName(parameter1, parameter2, ...) {
// code that uses parameter1, parameter2, etc.
}
// When calling the function:
functionName(argument1, argument2, ...);
Key Concepts:
- Declaration vs. Call: Parameters are defined in the function declaration; arguments are passed in the function call.
- Order Matters: Arguments are matched to parameters by their position.
- Optional Parameters: In JavaScript, if you don't pass an argument for a parameter, that parameter's value inside the function will be
undefined. - Default Parameters (ES6): You can provide default values for parameters, which will be used if no argument (or
undefined) is provided for that parameter during the function call.
Examples
2. Return Values (Outputs)
The return statement is used to send a value back from a function to the place where it was called. Functions don't have to return a value, but if they do, that value can then be used in your code.
Syntax
function functionName(parameters) {
// ... some code ...
return valueToReturn // Sends 'valueToReturn' back
}
Key Concepts:
- Exits Function: When a
returnstatement is executed, the function immediately stops executing, and control is returned to the caller. Any code afterreturnin the same function will not run. - Implicit
undefined: If a function does not have areturnstatement, or if it has an emptyreturn;, it implicitly returnsundefined. - Capturing the Value: You typically store the returned value in a variable.
Examples
Exercise: Parameters and Return Values
Complete the following functions using parameters and return values as specified.

