6.3.2 Using return
Statements
In the world of programming, functions are like magical spells that perform tasks and sometimes provide us with results. The return
statement is a crucial part of this magic, allowing functions to send back values to wherever they were called. In this section, we’ll explore how return
statements work, why they’re important, and how you can use them to make your JavaScript functions more powerful and efficient.
Understanding the return
Statement
The return
statement in JavaScript serves two primary purposes:
- Ending Function Execution: When a
return
statement is executed, it immediately stops the function’s execution. This means that any code after the return
statement within the same function will not run.
- Providing a Value: The
return
statement can send a value back to the part of the program that called the function. This value can be a number, string, object, or any other data type.
Let’s look at an example to understand these concepts better.
function checkAge(age) {
if (age >= 18) {
return 'You are an adult.';
} else {
return 'You are a minor.';
}
}
let message = checkAge(20);
console.log(message); // Outputs: You are an adult.
In this example, the function checkAge
uses a return
statement to send back a message based on the age provided. If the age is 18 or older, it returns ‘You are an adult.’ Otherwise, it returns ‘You are a minor.’ The function stops executing as soon as it hits a return
statement, ensuring that only one of the messages is returned.
How return
Affects Function Execution
When a function encounters a return
statement, it stops executing further lines of code within that function. This is particularly useful for:
- Exiting Early: If certain conditions are met, you can exit the function early, saving processing time and resources.
- Avoiding Unnecessary Calculations: By returning a result as soon as it’s determined, you prevent the function from performing unnecessary operations.
Consider the following example:
function findSquareRoot(number) {
if (number < 0) {
return 'Invalid number';
}
return Math.sqrt(number);
}
console.log(findSquareRoot(9)); // Outputs: 3
console.log(findSquareRoot(-1)); // Outputs: Invalid number
In this function, if the number is negative, it immediately returns ‘Invalid number’ and skips the square root calculation.
Writing Functions that Return Values
To practice using return
statements, let’s write a function that returns a letter grade based on a score. This will help reinforce the concept of using return
to provide meaningful results from a function.
Activity: Create a getGrade
Function
Your task is to write a function called getGrade
that takes a score as an argument and returns a corresponding letter grade. Here’s a guide to help you:
- Define the Function: Start by creating a function named
getGrade
.
- Use Conditional Statements: Use
if
, else if
, and else
to determine the grade based on the score.
- Return the Grade: Use
return
statements to send back the appropriate letter grade.
Here’s how you might implement this:
function getGrade(score) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'F';
}
}
let grade = getGrade(85);
console.log(`Your grade is ${grade}`); // Outputs: Your grade is B
In this function, the return
statement is used to provide a letter grade based on the score. The function checks the score against various thresholds and returns the appropriate grade.
Best Practices for Using return
Statements
- Return Early: If you can determine the result of a function early, use
return
to exit the function and avoid unnecessary processing.
- Keep It Simple: Ensure that your
return
statements are clear and concise. Avoid complex logic within the return
statement itself.
- Consistent Return Types: Try to ensure that your function returns the same type of value in all scenarios. This consistency makes your code easier to understand and debug.
Common Pitfalls
- Unreachable Code: Be cautious of placing code after a
return
statement within the same function. This code will never be executed, which can lead to confusion.
- Multiple Return Paths: While having multiple
return
statements in a function can be useful, it can also make the function harder to read. Ensure that the logic is clear and well-documented.
Optimization Tips
- Avoid Redundant Calculations: Use
return
to avoid performing calculations or operations that are not needed once a result is determined.
- Use Functions to Simplify Logic: Break down complex logic into smaller functions that each return a specific result. This makes your code more modular and easier to maintain.
Conclusion
The return
statement is a powerful tool in JavaScript that allows you to control the flow of your functions and provide results to the rest of your program. By understanding how to use return
effectively, you can write more efficient, readable, and maintainable code. Practice using return
in different scenarios to become more comfortable with its role in function execution.
Quiz Time!
### What does the `return` statement do in a JavaScript function?
- [x] Ends the function execution and provides a value back to the caller.
- [ ] Only ends the function execution.
- [ ] Only provides a value back to the caller.
- [ ] Pauses the function execution.
> **Explanation:** The `return` statement in JavaScript ends the function execution and provides a value back to the caller.
### What happens if a function does not have a `return` statement?
- [x] It returns `undefined`.
- [ ] It returns `null`.
- [ ] It causes an error.
- [ ] It returns an empty string.
> **Explanation:** If a function does not have a `return` statement, it implicitly returns `undefined`.
### In the function `checkAge`, what will be the output of `checkAge(16)`?
```javascript
function checkAge(age) {
if (age >= 18) {
return 'You are an adult.';
} else {
return 'You are a minor.';
}
}
```
- [ ] You are an adult.
- [x] You are a minor.
- [ ] Invalid age.
- [ ] No output.
> **Explanation:** The function checks if the age is 18 or older. Since 16 is less than 18, it returns 'You are a minor.'
### What is a common mistake when using `return` statements?
- [ ] Using them to end a function.
- [x] Placing code after a `return` statement.
- [ ] Using them to provide a value.
- [ ] Using them in conditional statements.
> **Explanation:** A common mistake is placing code after a `return` statement, which will never be executed.
### How can `return` statements help in optimizing code?
- [x] By ending function execution early.
- [ ] By making functions longer.
- [ ] By adding more calculations.
- [ ] By ignoring conditions.
> **Explanation:** `return` statements can help optimize code by ending function execution early, avoiding unnecessary calculations.
### What is the output of `getGrade(75)` in the `getGrade` function?
```javascript
function getGrade(score) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'F';
}
}
```
- [ ] A
- [ ] B
- [x] C
- [ ] D
> **Explanation:** The score 75 falls in the range for a 'C' grade, so the function returns 'C'.
### What type of value can a `return` statement provide?
- [x] Any data type.
- [ ] Only strings.
- [ ] Only numbers.
- [ ] Only objects.
> **Explanation:** A `return` statement can provide any data type, including numbers, strings, objects, etc.
### Why is it important to have consistent return types in a function?
- [x] It makes the code easier to understand and debug.
- [ ] It makes the code more complex.
- [ ] It reduces the function's flexibility.
- [ ] It increases execution time.
> **Explanation:** Consistent return types make the code easier to understand and debug, as the expected output is predictable.
### What will be the output of `console.log(findSquareRoot(-4))`?
```javascript
function findSquareRoot(number) {
if (number < 0) {
return 'Invalid number';
}
return Math.sqrt(number);
}
```
- [x] Invalid number
- [ ] 2
- [ ] -2
- [ ] NaN
> **Explanation:** The function checks if the number is negative and returns 'Invalid number' if true.
### True or False: A function can have multiple `return` statements.
- [x] True
- [ ] False
> **Explanation:** A function can have multiple `return` statements, typically used within conditional structures to return different values based on different conditions.