Function Return in JavaScript

A function can not only take input values (called parameters) and perform some calculations on them, it can also give back output values. These output values are said to be “returned” by a function. Therefore, a function return in JavaScript is the output values given out by a function.

Returning a value is an important part of a function in any programming language. We can later save the returned value into a variable or a constant and use them later on.

NOTE: If you are new to functions, you can check it out on our JavaScript Functions lesson.

Syntax:

function name(params) {
    // The "value" is what we are returning.
    return value;
}

The above syntax is explained as follows:

  • A function is being created having a name and params.
  • To return a value, we write the return keyword followed by a value that we want to return.

NOTE: A function stops executing or running when it reaches a return statement.


Example 1

function area(length, breadth) {
    // Returning the product of our parameters "length" and "breadth"
    return length * breadth;
}

// We can store the returned value in a variable or a constant.
var areaOfABook = area(10, 5);
const areaOfALand = area(100.15, 80.88);

console.log(areaOfABook);
console.log(areaOfALand);

Output

50
8100.132

Here, a simple function called area which returns the area of the provided parameters is reused twice, to return values and store in a variable called areaOfABook and a constant called areaOfLand.

Thus, we can say that a function is generally created for reusability purposes 😎.


Example 2

function totalCost(price1, price2, price3) {
    return price1 + price2 + price3;
}

var costOfEggs = 100, costOfMilk = 50, costOfBread = 25, costOfCheese = 250, costOfPotatoes = 175;

console.log("My breakfast shopping: " + totalCost(costOfEggs, costOfBread, costOfMilk));
console.log("My dinner shopping: " + totalCost(costOfEggs, costOfPotatoes, costOfCheese));

Output

My breakfast shopping: 175
My dinner shopping: 525

Note: We can also directly console.log() returned values.


In this way, a function return in JavaScript gives output values back to us.