How to return a value from a JavaScript function?

To return a value from a JavaScript function, use the return statement. The return statement sends a value back to the code that called the function and immediately exits the function.

Syntax

function functionName() {
    // function body
    return value;
}

Example: Basic Return Statement

<html>
<head>
    <script>
        function concatenate(name, age) {
            var val = name + age;
            return val;
        }
        
        function DisplayFunction() {
            var result = concatenate('John ', 20);
            document.write(result);
        }
    </script>
</head>
<body>
    <p>Click the following button to call the function</p>
    <form>
        <input type="button" onclick="DisplayFunction()" value="Result">
    </form>
</body>
</html>

Example: Multiple Return Types

<html>
<head>
    <script>
        function getNumber() {
            return 42;
        }
        
        function getString() {
            return "Hello World";
        }
        
        function getBoolean() {
            return true;
        }
        
        function getObject() {
            return {name: "John", age: 30};
        }
        
        function showResults() {
            document.write("Number: " + getNumber() + "<br>");
            document.write("String: " + getString() + "<br>");
            document.write("Boolean: " + getBoolean() + "<br>");
            document.write("Object: " + JSON.stringify(getObject()));
        }
    </script>
</head>
<body>
    <button onclick="showResults()">Show Return Values</button>
</body>
</html>

Example: Conditional Returns

<html>
<head>
    <script>
        function checkAge(age) {
            if (age >= 18) {
                return "Adult";
            } else {
                return "Minor";
            }
        }
        
        function testAges() {
            document.write("Age 25: " + checkAge(25) + "<br>");
            document.write("Age 16: " + checkAge(16) + "<br>");
        }
    </script>
</head>
<body>
    <button onclick="testAges()">Test Ages</button>
</body>
</html>

Key Points

  • Functions without a return statement return undefined
  • The return statement immediately exits the function
  • JavaScript functions can return any data type
  • You can have multiple return statements in conditional blocks

Conclusion

Use the return statement to send values back from JavaScript functions. Functions can return any data type including numbers, strings, booleans, objects, and arrays.

Updated on: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements