Came across a return statement? And wanna know what does return do in JavaScript? In this tutorial, you will learn about return statements used in JavaScript programming.

What is return and why use it?

The return statement is associated with functions, also known as methods. When a function declaration is made, it is usually done by keeping in mind that it will perform some particular task.

Thus, if a function call is made, that function must return a value to be used further.

To return a value we must use a return statement inside the function declaration.

Note: If the return statement is not used. The function by default returns undefined.

Let’s see the return statement with the help of JavaScript code.

Examples to Show What does Return Do in JavaScript?

Example 1: Use of return in a JavaScript function.


function number(){
    return 2;
}

console.log(number());  //2

The above example simply returns a number 2 if a function call is made.

Example 2: Return inside a parameterised function.


function number(num){
return num;
}
console.log(number(5));  //5

In the above example, the function accepts a number and simply returns it.

Example 3: Conditional based return.


function evenOdd(num) {
  if (num % 2 == 0) {
    return "even";
  } else {
    return "odd";
  }
}
console.log(evenOdd(2)); //even

In the above example, the function accepts a number and checks if it is even or odd and then returns a message depending on the number we passed in as a parameter. Therefore we can also use conditional-based returns.

Example 4: When the return is missing in a function.


function number(){
let num=5;
//return statement missing
}

console.log(number());  //undefined

Here, in the above example return is not defined. If a function call is made it by default returns undefined.

Do more with Return Statement in JavaScript

A return statement is not limited to just returning a single value or data. You can do more with return statements-

  1. Return multiple values at once like numbers, strings, boolean etc.
  2. You can also return an array
  3. Moreover, a return statement can be used to return an object.
  4. Finally, return statements are used to return promises in JavaScript.

Still not able to understand the use and working of the return statement? let us know in the comments.

Also, You may be interested to learn more about JavaScript-

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed