Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0

Sharpen your coding skills—try JavaScript challenges on TOOLX now!

advertisement

The return Statement in JavaScript

return statement in javascript

Return Statement

A function operates on its parameters which might lead to some output values. This output needs to be displayed to the user or it needs to be sent back to the calling function. Java Script allows sending the result back to the calling function by using the return statement.

The return statement begins with the return keyword followed by the variable or value, which must be returned to the calling function. The return statement can also be used to halt the function's execution and return control to the calling function. This is required when a particular condition is false or unexpected results are likely during code execution.

Script that calculates the factorial of a number using a function and displays the output to the user.

Example 1: Simple Function Return

function addNumbers(a, b) {
    return a + b;
}

let result = addNumbers(5, 3);
console.log(result); // Output: 8


Example 2: Conditional Return

function checkEvenOrOdd(number) {
    if (number % 2 === 0) {
        return "Even";
    } else {
        return "Odd";
    }
}

console.log(checkEvenOrOdd(4)); // Output: Even
console.log(checkEvenOrOdd(7)); // Output: Odd


Example 3: Early Return

function divide(a, b) {
    if (b === 0) {
        return "Error: Division by zero!";
    }
    return a / b;
}

console.log(divide(10, 2)); // Output: 5
console.log(divide(10, 0)); // Output: Error: Division by zero!


JavaScript return statement javaScript return statement simple function return Conditional return early return javascript return statement with examples

advertisement