Javascript - Function Function Return

Introduction

Functions in ECMAScript need not specify whether they return a value.

Any function can return a value at any time by using the return statement followed by the value to return.

Consider this example:

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

The sum() function adds two values together and returns the result.

There is no declaration indicating that the function returns a value.

This function can be called using the following:

var result = sum(5, 10);

A function stops executing and exits immediately when it encounters the return statement.

For example:

function sum(num1, num2) {
   return num1 + num2;
   console.log("Hello world");    //never executed
}

In this example, the console.log will never be called because it appears after the return statement.

You can have more than one return statement in a function, like this:

function diff(num1, num2) {
   if (num1 < num2) {
       return num2 - num1;
   } else {
       return num1 - num2;
   }
}

Here, the diff() function determines the difference between two numbers.

If the first number is less than the second, it subtracts the first from the second; otherwise it subtracts the second from the first.

The return statement can be used without a return value.

The function stops executing immediately and returns undefined as its value.

function displayMessage(name, message) {
    return;
    console.log("Hello " + name + ", " + message);    //never called
}

Strict mode places several restrictions on functions:

  • No function can be named eval or arguments.
  • No named parameter can be named eval or arguments.
  • No two named parameters can have the same name.