Index

Assignment 12 CB - Factorial

Using the JavaScript language, have the function factorial(num) take the num parameter being passed and return the factorial of it (ie. if num = 4, return (4 * 3 * 2 * 1)).

Enter an positive integer in the input field below.

$(document).ready(function() { function factorial(n) { if (n === 0) { return 1; } else { return n * factorial(n - 1); } } $('.calculate').click(function() { var numString = $('.data input').val(), numValue = numString * 1; if (numString === '' || isNaN(numValue) || parseInt(numValue) !== numValue) { $('.result p').html('Please enter an integer in the input field.'); } else { $('.result p').html(numValue + '! = <span>' + factorial(numValue) + '</span>'); } }); });