Javascript Interview Question Number Get factorial number

Introduction

Write a function that calculates the factorial of a given number recursively.


function factorial(n) {
    //your code here
}


console.log(factorial(4));
console.log(factorial(5));
console.log(factorial(6));


/**
 * @function {public static} factorial
 *
 * Recursively calculates the factorial of a given number.
 *
 * @param {Integer} n - the number to calculate.
 *
 * @return the factorial of the given number.
 */
function factorial(n) {
    if (n > 1) {
        return n * factorial(n-1);
    }

    return 1;
}


console.log(factorial(4));
console.log(factorial(5));
console.log(factorial(6));

/*
Output: ($ /usr/bin/node 001.js)
24
120
720
*/



PreviousNext

Related