Functions use return to send values back:
function add(a, b) {
return a + b;
}
const result = add(2, 3); // result = 5
The function computes a + b and returns it to the caller.
return vs print
Beginners often confuse these:
// Printing - shows in console
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice"); // Displays "Hello, Alice"
const result = greet("Bob"); // result is undefined
// Returning - gives value back
function greet(name) {
return "Hello, " + name;
}
const message = greet("Alice"); // message = "Hello, Alice"
console.log(message); // Now it displays
print shows output. return provides values for further use.
How return Works
return does two things:
- Sends a value to the caller
- Exits the function immediately
function example() {
console.log("Before return");
return 42;
console.log("After return"); // Never executes
}
const value = example();
// Logs: "Before return"
// value = 42
Early Returns
Exit functions early:
function divide(a, b) {
if (b === 0) {
return null; // Early exit
}
return a / b;
}
Multiple Return Statements
Different conditions can return different values:
function getStatus(score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "F";
}
Implicit Returns
Some languages have implicit returns:
// JavaScript - undefined if no return
function noReturn() {
const x = 5;
}
noReturn(); // undefined
// Ruby - last expression
def add(a, b)
a + b # Automatically returned
end
// Rust - no semicolon
fn add(a: i32, b: i32) -> i32 {
a + b // Returned (no semicolon)
}
Returning Multiple Values
JavaScript - arrays or objects:
function getUser() {
return ["Alice", 30];
}
const [name, age] = getUser();
// Or objects
function getUser() {
return { name: "Alice", age: 30 };
}
const { name, age } = getUser();
Python - tuples:
def get_coordinates():
return 10, 20
x, y = get_coordinates()
Go - multiple return values:
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
result, err := divide(10, 2)
Returning Functions
Functions can return other functions:
function createMultiplier(factor) {
return function(num) {
return num * factor;
};
}
const double = createMultiplier(2);
double(5); // 10
Void Functions
Functions that don't return meaningful values:
function logMessage(msg) {
console.log(msg);
// No return statement = returns undefined
}
// Explicit void in TypeScript
function logMessage(msg: string): void {
console.log(msg);
}
Return Type Annotations
TypeScript:
function add(a: number, b: number): number {
return a + b;
}
Python type hints:
def add(a: int, b: int) -> int:
return a + b
Chaining Returns
const result = parse(clean(validate(input)));
Each function's return value becomes the next function's input.
Return in Different Contexts
Loops:
function findFirst(arr, condition) {
for (const item of arr) {
if (condition(item)) {
return item; // Exits function, not just loop
}
}
return null; // Not found
}
Callbacks:
array.map(item => item * 2); // Implicit return in arrow function
array.map(item => { return item * 2; }); // Explicit
Common Mistakes
Forgetting return:
// Wrong
function add(a, b) {
a + b; // Doesn't return
}
// Correct
function add(a, b) {
return a + b;
}
Unreachable code after return:
function example() {
return 42;
console.log("Never runs"); // Dead code
}
Expecting printed values:
function bad() {
console.log(42);
}
const x = bad(); // x is undefined, not 42
Best Practices
- Return early for error cases
- Be consistent with return types
- Avoid side effects in return expressions
- Use descriptive names for return values
Further Reading
MDN's return statement documentation covers JavaScript behavior.
Clean Code by Robert Martin discusses function design including return values.
The return statement is fundamental to function design.
0 comments