The return
statement in JavaScript is used to exit a function and optionally provide a value back to the code that called the function. Here’s how it works with examples:
function functionName(arguments) { // Function body return value; }
Explanation:
functionName
: This is the name you give to your function.arguments
: These are optional values that you can pass to the function when you call it.// Function body
: This is where you write the code that the function will execute.return value
: This is the value (or expression) that you want to send back from the function. Thereturn
statement exits the function after the value is returned.
Example 1: Returning a Calculated Value
This function calculates the area of a rectangle and returns the result:
function getArea(width, height) { const area = width * height; return area; } // Calling the function and storing the returned value const rectangleArea = getArea(5, 4); console.log(rectangleArea); // Output: 20
In this example, the getArea
function takes two arguments, width
and height
. It calculates the area by multiplying them and then uses the return
statement to send the area
value back to the code that called it. The result is stored in the rectangleArea
variable and then logged to the console.
Example 2: Returning Early
This function checks if a number is even and returns a message accordingly:
function isEven(number) { if (number % 2 === 0) { return "The number is even."; } else { // No return statement here, function continues } return "The number is odd."; } const evenResult = isEven(10); console.log(evenResult); // Output: "The number is even." const oddResult = isEven(7); console.log(oddResult); // Output: "The number is odd." (evenResult is not affected)
Here, the isEven
function uses an if
statement to check if the number is divisible by 2 (even). If it is, it uses return
to exit the function and send back a message. Even though there’s another return
statement later, it’s not reached because the function already exited with the first return
.
Key Points:
- A function can only have one
return
statement, but it can be placed anywhere within the function body.If a function doesn’t have an explicitreturn
statement, it implicitly returnsundefined
.