Value Returning Functions

Return Command

Let's start this topic by giving an example with one of the functions available in the programming language. The pow method of the Math class is a function that takes two values ​​from the outside and returns the result by calculating the power of the first number from the second number degree. Since it returns a value, it can be used by equating it to a variable as follows.

var a=Math.pow(2,4);
document.write(a);

In the above example, 2 to the 4th power is calculated by the function and the result is returned and assigned to variable a. If we do not want to use this function ready-made and write it ourselves:

function force(base, us)
{
    var i, result;
    result=1;
    
    for(i=1;i<=us;i++)
    {
        result=result*base;
        }
    document.write(result);
}

The function we wrote above calculates the power of the given number and writes it to the screen. But we cannot equate this function anywhere. For example , we cannot use a=force(3,5) . Because this function does not return a value.

Now let's return the value of the result variable with the return command.

function force(base, us)
{
    var i, result;
    result=1;
    
    for(i=1;i<=us;i++)
    {
        result=result*base;
        }
    return result;
}

Now we can equate the function wherever we want and even use it in mathematical operations. For example;

var x = force(2.4) + force(3.5) - force(4.2)

Each time the force function is called, the result is returned and the result of that operation is written in the relevant place.

***A function can only return one value. It would be silly otherwise. 

javascript value returning functions, return statement, return method examples

EXERCISES

Calculating Combination in JavaScript Try It
By clicking the Try It Yourself button, you can see, change, and see the result, for example, your codes.
 
In our example, a function that calculates the factorial is created as follows. This function returns the result by calculating the factorial of the incoming number.
 
When the button is clicked, this function is used by calling it from another place.
function factorial(number)
{
var i, result;
result=1;
 
for(i=1;i<=number;i++)
{
result=result*i;
}
 
return result;
 
}

 



COMMENTS




Read 498 times.

Online Users: 409



javascript-value-returning-functions