Return values
- Node.js course
- Beginner
- Lesson 72/116
- 4 min
Learn to return a value from a function with return.
Return value
The return keyword sends a value back from a function and returns control to the caller. When return runs, the rest of the function does not; the function ends.
Example: function double(n) { return n * 2; }. Here return n * 2 gives the caller twice n. The call double(5) returns 10; you can assign this result to a variable or print it with console.log.
If you omit return, the function still runs but produces no value; the result is undefined. Forgetting return in a computing function is a common mistake.
Without return, undefined
If a function has no return, or return is followed by no value, JavaScript returns undefined. This is not an error; it runs silently. For side-effect functions (printing, saving to a file) this is normal.
Example: function log(msg) { console.log(msg); }. This function returns nothing; in const result = log('hello'), result is undefined. But 'hello' is still printed.
Forgetting return in a computing function is one of the most common mistakes. If you expected a value but got undefined, first check whether return is there.
Practice Compute the sum
Define a function add(a, b) whose body returns a + b. Print the result of add(15, 27) with console.log.
Starter code
// Define add and print the call resultSample solution
function add(a, b) {
return a + b;
}
console.log(add(15, 27));Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add the return
function double(n) { ____ n * 2; }
function double(n) { return n * 2; }
Explanation: return n * 2 sends the value back to the caller.
2 What does a function without return give?
- null
- An empty string
- 0
- undefined Correct answer
Explanation: without return JavaScript gives undefined.
3 Match the return concepts
| Term | Meaning |
|---|---|
return n * 2 |
Expression that returns a value |
undefined |
Result when return is missing |
double(5) |
Call returning 10 |
function double |
Function definition |