How to Return Value from Function in JavaScript: Simple Guide
In JavaScript, you use the
return keyword inside a function to send a value back to where the function was called. The function stops running after return and gives back the specified value.Syntax
The basic syntax to return a value from a function uses the return keyword followed by the value you want to send back. This value can be a number, string, object, or any expression.
- functionName: The name of your function.
- parameters: Optional inputs your function can use.
- return value: The value sent back to the caller.
javascript
function functionName(parameters) { return value; }
Example
This example shows a function that adds two numbers and returns the result. When you call the function, it gives back the sum, which you can store or use immediately.
javascript
function add(a, b) { return a + b; } const result = add(5, 3); console.log(result);
Output
8
Common Pitfalls
One common mistake is forgetting the return keyword, which makes the function return undefined by default. Another is placing code after return, which will never run because return stops the function immediately.
javascript
function wrongAdd(a, b) { a + b; // Missing return, so returns undefined } function correctAdd(a, b) { return a + b; // Correct way }
Quick Reference
| Concept | Description |
|---|---|
| return | Sends a value back from a function and stops execution |
| Function call | Where you get the returned value |
| No return | Function returns undefined by default |
| After return | Code after return is ignored |
Key Takeaways
Use the return keyword to send a value back from a function.
Functions without return give undefined by default.
Code after return inside a function does not run.
Returned values can be stored or used immediately.
Always check you include return when you want a result.