Day 5 – Factorial of a Number in JavaScript: Recursion vs Loop

 ๐Ÿ”ฅ JavaScript DSA Interview Series – Day 5


๐Ÿง  Problem: Find the factorial of a number using both loop and recursion



---


✅ What is Factorial?


The factorial of a number n is the product of all positive integers less than or equal to n.

๐Ÿ“Œ n! = n × (n−1) × (n−2) × ... × 1

Example:

5! = 5 × 4 × 3 × 2 × 1 = 120



---


๐Ÿ“Œ Iterative (Loop) Approach:


function factorialLoop(n) {

  let result = 1;

  for (let i = 2; i <= n; i++) {

    result *= i;

  }

  return result;

}



---


๐Ÿ“Œ Recursive Approach:


function factorialRecursive(n) {

  if (n === 0 || n === 1) return 1;

  return n * factorialRecursive(n - 1);

}



---


⚠️ Edge Case:


0! is 1


Negative numbers are not valid for factorial




---


๐Ÿ’ก Tips to Remember:


Use recursion only for small inputs (can cause stack overflow)


Loop is efficient and safe for interviews


Recursive solution shows understanding of function calls and base conditions


http://youtube.com/post/Ugkx1JuFK5mB2cSUAX8Yu0N6eFe8RuioUQ3Z?si=vN94FOnh01Dqq6A-



Comments

Popular posts from this blog

Day 4 – Palindrome Number in JavaScript Without Converting to String

Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge