Javascript Data Structure Tutorial - Javascript Functions








JavaScript can define both value-returning functions and void-returning functions.

Example

The following code demonstrates how to create a value-returning functions and call it in JavaScript.


function factorial(number) { //from  w w w.j  av a  2 s .c o m
    var product = 1; 
    for (var i = number; i >= 1; --i) { 
        product *= i; 
    } 
    return product; 
} 
console.log(factorial(2)); 
console.log(factorial(3)); 
console.log(factorial(4)); 
console.log(factorial(5)); 
console.log(factorial(10));
console.log(factorial(20));




Example 2

The following code illustrates how to write a function to operate on values.


function curve(arr, amount) { 
    for (var i = 0; i < arr.length; ++i) { 
        arr[i] += amount; 
    } 
} 

var grades = [77, 73, 74, 81, 90, 34, 21, 12, 34, 54,]; 
curve(grades, 5); 
console.log(grades); 




Note

All function parameters in JavaScript are passed by value.

The reference objects, such as arrays, are passed to functions by reference, as was demonstrated in the code above.

Recursion

Function calls can be made recursively in JavaScript.

The factorial() function can be written recursively, like this:

function factorial(number) { 
    if (number == 1) { 
        return number; 
    } 
    else { 
        return number * factorial(number-1); 
    } 
} 
console.log(factorial(5)); 
console.log(factorial(15)); 
console.log(factorial(25)); 
console.log(factorial(50));