Academic Block

JavaScript Return Statement Get Certified

The return statement is how a function sends a value back to the code that called it. It’s one of the most important tools for making functions genuinely reusable, rather than just blocks of code that print things to the console.

In this lesson, you will learn how return works, how early returns (guard clauses) simplify code, the difference between return and console.log, and how to return multiple values.

Basic return Usage

A return statement sends a value back to wherever the function was called, so it can be stored, logged, or used in further calculations.

What this code does: return sends a value back to the caller and exits the function. circleArea(5) computes the area and returns it; that value is stored in area and printed.

function circleArea(radius) {
    return Math.PI * radius * radius;
}
let area = circleArea(5);
console.log(area);

return Immediately Exits the Function

As soon as a return statement runs, the function stops executing. Any code written after it in the same block is never reached.

What this code does: As soon as return runs, the function stops. The console.log after the return never executes. The function returns true or false.

function checkStock(quantity) {
    return quantity > 0;
    console.log("This line never runs.");
}
console.log(checkStock(5));
console.log(checkStock(0));

Early Returns (Guard Clauses)

A common pattern is to return early when a certain condition is met, avoiding deeply nested if...else blocks. This is often called a guard clause.

What this code does: Multiple early returns act as guard clauses—each condition returns a different label. Membership years of 0, 3, and 7 produce different discount messages.

function getDiscountLabel(membershipYears) {
    if (membershipYears < 1) {
        return "No discount";
    }
    if (membershipYears < 5) {
        return "5% loyalty discount";
    }
    return "10% loyalty discount";
}
console.log(getDiscountLabel(0));
console.log(getDiscountLabel(3));
console.log(getDiscountLabel(7));

Each condition returns immediately once it matches, so there’s no need for else blocks at all.

Using return for Input Validation

Guard clauses are especially useful for exiting a function early when the input is invalid, before running the rest of the logic.

What this code does: Guard clauses check for invalid input first and return an error message. Only valid inputs reach the BMI calculation. Invalid height returns a message instead of a number.

function calculateBmi(weightKg, heightM) {
    if (heightM <= 0) {
        return "Invalid height";
    }
    if (weightKg <= 0) {
        return "Invalid weight";
    }
    return (weightKg / (heightM * heightM)).toFixed(1);
}
console.log(calculateBmi(70, 1.75));
console.log(calculateBmi(70, 0));

return Without a Value

return can be used on its own, with no value, simply to exit the function early. In this case, the function returns undefined.

What this code does: A bare return; exits early and returns undefined. Negative numbers are ignored; only positive numbers are logged.

function logIfPositive(number) {
    if (number <= 0) {
        return;
    }
    console.log(number, "is positive.");
}
logIfPositive(5);
logIfPositive(-2);

Functions Without a return Statement

If a function never reaches a return statement at all, it implicitly returns undefined once it finishes running.

What this code does: A function with no return always returns undefined. printReceipt only logs; storing its result in output gives undefined.

function printReceipt(itemName, price) {
    console.log(itemName + ": $" + price);
}
let output = printReceipt("Coffee", 4.5);
console.log(output);

return vs. console.log

A common source of confusion for beginners is mixing up return and console.log. console.log only displays a value in the console; it doesn’t hand that value back to the rest of the program.

What this code does: console.log is for display; return is for giving a value to the caller. The log version’s result is undefined; the return version’s result is 10 and can be reused.

function doubleWithLog(number) {
    console.log(number * 2);
}
function doubleWithReturn(number) {
    return number * 2;
}
let loggedResult = doubleWithLog(5);
let returnedResult = doubleWithReturn(5);
console.log("From console.log version:", loggedResult);
console.log("From return version:", returnedResult);

Only doubleWithReturn actually gives us a usable value; doubleWithLog just prints its result and returns undefined.

Returning Multiple Values

A function can only return one value directly, but that value can be an array or an object containing multiple pieces of data.

What this code does: To return several related values, return an object (or array). getMinMax returns both min and max in one object, which are then printed.

function getMinMax(numbers) {
    return {
        min: Math.min(...numbers),
        max: Math.max(...numbers)
    };
}
const result = getMinMax([12, 5, 30, 8, 19]);
console.log(result.min, result.max);

You can also return an array and destructure it directly at the call site.

What this code does: Returning an array lets the caller use destructuring to unpack the values. The full name is split into first and last name, which are printed separately.

function splitFullName(fullName) {
    return fullName.split(" ");
}
const [firstName, lastName] = splitFullName("Michael Johnson");
console.log(firstName);
console.log(lastName);

return Inside a Loop

When return is used inside a loop within a function, it exits the entire function immediately, not just the loop. This is useful for stopping a search as soon as a match is found.

What this code does: Early return inside a loop stops searching as soon as a match is found. If no user matches the id, the function returns null after the loop.

function findUserById(users, id) {
    for (let i = 0; i < users.length; i++) {
        if (users[i].id === id) {
            return users[i];
        }
    }
    return null;
}
const users = [
    { id: 1, name: "Sofia" },
    { id: 2, name: "James" },
    { id: 3, name: "Lena" }
];
console.log(findUserById(users, 2));
console.log(findUserById(users, 99));

As soon as a matching user is found, return exits the function entirely — the loop never checks the remaining users.

Watch Out for Automatic Semicolon Insertion

Placing a newline directly after return and before the value can cause unexpected behavior, because JavaScript may automatically insert a semicolon right after return.

What this code does: A newline after return triggers automatic semicolon insertion, so the function returns undefined and the object is never returned. Keep the value on the same line as return.

function getUserObject() {
    return
    {
        name: "Michael"
    };
}
console.log(getUserObject());

Because of automatic semicolon insertion, this function actually returns undefined — the object literal on the next line is never reached. Always keep the returned value on the same line as return.

Practical Example

Let’s use return with guard clauses to validate a password before accepting it.

What this code does: A practical validation function with sequential guard clauses. Each failed rule returns an error message; only a valid password reaches the final success return.

function validatePassword(password) {
    if (password.length < 8) {
        return "Password must be at least 8 characters.";
    }
    if (!/[0-9]/.test(password)) {
        return "Password must contain at least one number.";
    }
    return "Password is valid.";
}
console.log(validatePassword("abc"));
console.log(validatePassword("abcdefgh"));
console.log(validatePassword("abcdefg1"));

Common Mistakes With return

  • Confusing console.log with return, and expecting a logged value to be usable elsewhere.
  • Writing code after a return statement in the same block, not realizing it will never run.
  • Putting a newline between return and the value being returned, accidentally returning undefined due to automatic semicolon insertion.
  • Forgetting to return a value at all, and being surprised the function’s result is undefined.
  • Trying to return more than one separate value directly, instead of grouping them into an array or object.

Best Practices for return

  • Use guard clauses with early return statements to avoid deeply nested conditionals.
  • Always keep the returned expression on the same line as the return keyword.
  • Return objects or arrays when a function needs to provide multiple related values.
  • Prefer returning values from functions over relying on console.log for anything other than debugging.
  • Keep functions predictable — try to always return the same type of value from a given function, regardless of the input.

Quick Summary

  • return sends a value back to the caller and immediately exits the function.
  • return with no value returns undefined.
  • A function without any return statement also returns undefined.
  • Guard clauses use early return statements to simplify conditional logic.
  • Multiple values can be returned together using an array or object.
  • Never place a newline between return and the value you intend to return.

Try It Yourself

Modify the function below. Try adding another guard clause, or changing what gets returned for each condition.

What this code does: Practice example: change the temperature thresholds or labels, then click Test My Code to see how early returns classify different values.

function classifyTemperature(celsius) {
    if (celsius < 0) {
        return "Freezing";
    }
    if (celsius < 15) {
        return "Cold";
    }
    if (celsius < 25) {
        return "Mild";
    }
    return "Hot";
}
console.log(classifyTemperature(-5));
console.log(classifyTemperature(20));
console.log(classifyTemperature(30));
Tip: If you’re debugging a function and its result is unexpectedly undefined, check two things first: did you actually write a return statement, and is the value on the same line as the return keyword?

Understanding return is essential before moving on to closures, recursion, and more advanced JavaScript concepts.

🧪 Test Your JavaScript Code

Edit the code on the left and click “Run Code” to see the console output on the right.

📝 JavaScript Code
👁 Console Output

Click “Run Code” to see the output here.

Ctrl + Enter to run code Esc to close