Skip to content

JavaScript Function Return statement

  • by

The return statement in JavaScript allows a function to return a value when it is called. This value can be used for further processing or stored in a variable. The return statement immediately exits the function and any code after it will not be executed.

The syntax of the return statement in JavaScript is as follows:

return expression;

Here, expression is the value that the function will return. It can be any valid JavaScript expression, including a variable, a literal value, or a more complex expression.

Here’s an example of a function that returns a value:

function addNumbers(num1, num2) {
  return num1 + num2;
}

JavaScript Function Return Example

Simple example code of a function that uses the return statement to return a value:

<!DOCTYPE html>
<html>
<head>
  <script>
    function calculateArea(width, height) {
        var area = width * height;
        return area;
    }

    var rectangleArea = calculateArea(5, 7);
    console.log(rectangleArea); // Output: 35

  </script>
</head>
</html>

Output:

JavaScript Function Return statement

Another example

function calculateTotalPrice(price, taxRate) {
  var taxAmount = price * taxRate;
  var totalPrice = price + taxAmount;
  return totalPrice;
}

var itemPrice = 10;
var taxRate = 0.2;
var totalPrice = calculateTotalPrice(itemPrice, taxRate);
console.log("The total price is: " + totalPrice); // Output: The total price is: 12

To use the function, we define two variables itemPrice and taxRate, and then call the calculateTotalPrice function with these variables as arguments. The returned value is stored in the totalPrice variable.

Comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *