Function Parameters and Return Values
Function Parameters and Return Values
Functions receive inputs via parameters and send outputs back to the caller via return values. Mastering parameter defaults, rest parameters, and return semantics is essential for writing robust JavaScript functions.
1. Parameters vs. Arguments
While often used interchangeably in casual conversation, there is a clear distinction:
- Parameters: The variable names listed in the function definition.
- Arguments: The real values passed into the function when you invoke it.
2. The return Statement
The return statement does two things:
- 1It immediately stops the execution of the function.
- 2It sends the evaluated value back to the caller.
return statement (or has an empty return;), it automatically returns undefined!3. Default Parameters (ES6)
What happens if a caller forgets to pass an argument? Without defaults, missing arguments become undefined. In ES6, you can specify default values directly in the parameter list:
4. Variable Number of Arguments: Rest Parameters (...args)
What if you want to write a function that can accept any number of inputs (e.g. summing 3, 5, or 100 numbers)? Use the Rest Parameter (...):
5. Returning Multiple Values via Objects or Arrays
A function in JavaScript can technically only return a single value. To return multiple values, return an object or an array:
Practice Quiz
return statement?tax if invoked as calculateTotal(500) where the function is defined as function calculateTotal(price, tax = 0.1) { return price * tax; }?return statement in the same execution branch ever execute?Arrow Functions (Basic)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Defining and Calling Functions | Arrow Functions (Basic) |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.