How to return a value from a function

Description

Functions can return a value using the return statement followed by the value to return.


function sum(num1, num2) {//from w w  w  . j a v  a 2s .  c o m
   return num1 + num2;
}
var result = sum(5, 10);
console.log(result);

The code above generates the following result.

Example

A function stops executing and exits immediately when it encounters the return statement. Therefore, any code after a return statement will never be executed. For example:


function sum(num1, num2) {//from w  w  w  . j a v a 2 s  .c om
   return num1 + num2;
   console.log("Hello world");    //never executed
}
var result = sum(5, 10);
console.log(result);

The code above generates the following result.

Example 2

It's also possible to have more than one return statement in a function, like this:


function diff(num1, num2) {//w w w. j a v a2 s  .  c o m
   if (num1 < num2) {
       return num2 - num1;
   } else {
       return num1 - num2;
   }
}
var result = diff(5, 10);
console.log(result);

The code above generates the following result.

Example 3

The return statement can be used without return value, and will return undefined.


function sayHi(name, message) {//from  w  w  w . j  ava  2 s  . co m
   return;
   console.log("Hello " + name + ", " + message);    //never called
}
var result = sayHi(5, 10);
console.log(result);

The code above generates the following result.

Note

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.




















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions