🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The factorial of a number is the product of all positive integers less than or equal to that number. In JavaScript, you can compute the factorial using various methods such as recursion, iteration, and higher-order functions. This guide will walk you through different ways to compute the factorial in JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts a positive integer.
- Calculates and returns the factorial of that number using different methods.
Example:
Input:
5Output:
120Input:
3Output:
6
Solution Steps
- Read the Input Number: Accept or define the number directly in the program.
- Handle Base Case: Return
1if the input number is0or1. - Calculate Factorial: Implement different methods (recursion, iteration, functional programming).
- Display the Result: Output the calculated factorial for each method.
Method 1: Recursive Approach
// JavaScript Program to Find the Factorial of a Number Using Recursion
// Author: https://www.javaguides.net/
function factorialRecursive(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
let number = 5;
let result = factorialRecursive(number);
console.log(`The factorial of ${number} using recursion is: ${result}`);
Output:
The factorial of 5 using recursion is: 120
Explanation:
- This function uses recursion to calculate the factorial. The base case returns
1for0!and1!. For other numbers, it recursively multiplies the number byfactorial(n-1).
Method 2: Iterative Approach
// JavaScript Program to Find the Factorial of a Number Using Iteration
// Author: https://www.javaguides.net/
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
result = factorialIterative(number);
console.log(`The factorial of ${number} using iteration is: ${result}`);
Output:
The factorial of 5 using iteration is: 120
Explanation:
- The iterative approach uses a
forloop to calculate the factorial. It starts from1and multiplies by each subsequent number until it reachesn.
Method 3: Using Higher-Order Functions (Array reduce)
// JavaScript Program to Find the Factorial of a Number Using Array reduce
// Author: https://www.javaguides.net/
function factorialUsingReduce(n) {
if (n === 0 || n === 1) {
return 1;
}
return [...Array(n).keys()].map(i => i + 1).reduce((acc, val) => acc * val, 1);
}
result = factorialUsingReduce(number);
console.log(`The factorial of ${number} using reduce is: ${result}`);
Output:
The factorial of 5 using reduce is: 120
Explanation:
- This method leverages JavaScript’s
Array.reduce()to calculate the factorial. An array from1tonis created and then reduced by multiplying each element.
Conclusion
This JavaScript program demonstrates three methods to calculate the factorial of a number:
- Recursion is elegant but can be less efficient for large numbers due to stack overflow risks.
- Iteration is straightforward and memory efficient.
- Array reduce provides a functional programming approach, making the code concise and leveraging JavaScript’s higher-order functions.
Each method has its own advantages depending on the scenario and size of the input number.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment