JavaScript: Calculate the factorial of a number
JavaScript fundamental (ES6 Syntax): Exercise-238 with Solution
Write a JavaScript program to calculate the factorial of a number.
- Use recursion.
- If n is less than or equal to 1, return 1.
- Otherwise, return the product of n and the factorial of n - 1.
- Throw a TypeError if n is a negative number.
Sample Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculate the factorial of a number</title>
</head>
<body>
</body>
</html>
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const factorial = n =>
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1
? 1
: n * factorial(n - 1);
console.log(factorial(1));
console.log(factorial(5));
console.log(factorial(7));
Sample Output:
1 120 5040
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-238-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to generate an array, containing the Fibonacci sequence, up until the nth term.
Next: Write a JavaScript program to escape a string to use in a regular expression.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join