44. The return Statement
The return statement is used to send a value back from a function, allowing the calling code to use the result of the function's execution.
How return Works
- It stops the function execution immediately.
- It sends the specified value back to the caller.
Example: Calculating and Returning
javascript function calculateTax(amount) { const taxRate = 0.10; const tax = amount * taxRate; return tax;
// Any code below return is unreachable and ignored
// console.log('This will not execute');
}
let purchaseTotal = 200; let taxDue = calculateTax(purchaseTotal);
console.log(Tax owed: $${taxDue}); // Output: Tax owed: $20
Functions Without return
If a function does not contain an explicit return statement, it implicitly returns undefined.