Start learning free

LESSON 43 OF 671 · FUNCTIONS I

Returning from functions in JavaScript in JavaScript

Lesson Read the full explanation

We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):

function plusThree(num) {
	return num + 3;
}

let answer = plusThree(5);

answer has the value 8.

plusThree takes an argument for num and returns a value equal to num + 3.


No return statement:

In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.

let sum = 0;

function addToSum(num) {
	sum += num;
}

let returned = addToSum(3);

console.log(sum); // Output: 3
console.log(returned); // Output: undefined

addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is undefined.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · FUNCTIONS I

    Returning From A Function in JavaScript, explained

    Introduction

    In JavaScript, functions are fundamental building blocks that allow you to encapsulate code for reuse and modularity. One of the key features of functions is their ability to return values. This lesson will explore how to use the return statement in JavaScript functions, its significance, and common scenarios where it is particularly useful.

    Understanding the Basics

    At its core, a function in JavaScript can take inputs (arguments) and produce an output using the return statement. The return statement stops the execution of the function and sends a value back to the calling code.

    Consider the following simple example:

    function multiplyByTwo(num) {
        return num * 2;
    }
    
    let result = multiplyByTwo(4); // result is 8
    

    In this example, the function multiplyByTwo takes a number as an argument, multiplies it by two, and returns the result. The returned value is then stored in the variable result.

    Main Concepts

    Let's delve deeper into the key concepts and techniques involved in using the return statement:

    • Immediate Return: The return statement can be placed anywhere in the function. Once it is executed, the function stops, and the specified value is returned.
    • Returning Expressions: You can return the result of an expression directly.
    • Returning Objects: Functions can also return complex data types like objects and arrays.

    Here is an example that demonstrates these concepts:

    function createUser(name, age) {
        return {
            name: name,
            age: age
        };
    }
    
    let user = createUser('Alice', 30);
    console.log(user); // Output: { name: 'Alice', age: 30 }
    

    Examples and Use Cases

    Let's explore some examples and real-world use cases:

    function calculateArea(radius) {
        if (radius <= 0) {
            return 'Invalid radius';
        }
        return Math.PI * radius * radius;
    }
    
    console.log(calculateArea(5)); // Output: 78.53981633974483
    console.log(calculateArea(-1)); // Output: Invalid radius
    

    In this example, the function calculateArea returns the area of a circle if the radius is positive. If the radius is non-positive, it returns an error message.

    Common Pitfalls and Best Practices

    Here are some common mistakes to avoid and best practices to follow:

    • Unreachable Code: Any code after a return statement will not be executed. Ensure that your logic accounts for this.
    • Consistent Return Types: Try to return consistent data types from your functions to avoid unexpected behavior.
    • Clear and Descriptive: Write clear and descriptive return statements to make your code more readable and maintainable.

    Advanced Techniques

    Let's look at some advanced techniques involving the return statement:

    function outerFunction() {
        function innerFunction() {
            return 'Hello from inner function';
        }
        return innerFunction;
    }
    
    let inner = outerFunction();
    console.log(inner()); // Output: Hello from inner function
    

    In this example, the outerFunction returns the innerFunction, demonstrating how functions can return other functions.

    Code Implementation

    Here is a well-commented code snippet demonstrating the correct use of the return statement:

    // Function to calculate the factorial of a number
    function factorial(n) {
        // Base case: if n is 0, return 1
        if (n === 0) {
            return 1;
        }
        // Recursive case: return n * factorial of (n-1)
        return n * factorial(n - 1);
    }
    
    console.log(factorial(5)); // Output: 120
    

    Debugging and Testing

    Here are some tips for debugging and testing functions with return statements:

    • Use Console Logs: Use console.log to print intermediate values and understand the flow of your function.
    • Write Test Cases: Write test cases to verify the correctness of your functions. Use testing frameworks like Jest or Mocha for comprehensive testing.
    // Example test case for the factorial function
    console.assert(factorial(5) === 120, 'Test Case 1 Failed');
    console.assert(factorial(0) === 1, 'Test Case 2 Failed');
    

    Thinking and Problem-Solving Tips

    Here are some strategies for approaching problems related to functions and return statements:

    • Break Down the Problem: Divide complex problems into smaller, manageable parts and solve each part step-by-step.
    • Practice Regularly: Regular practice will help you become more comfortable with functions and return statements. Try coding exercises and projects to improve your skills.

    Conclusion

    In this lesson, we covered the importance of the return statement in JavaScript functions, explored various examples and use cases, discussed common pitfalls and best practices, and introduced advanced techniques. Mastering the use of the return statement is crucial for writing efficient and maintainable code.

    Keep practicing and exploring further applications to deepen your understanding.

    Additional Resources

    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free