Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Factorial function returning NAN

I am new to javascript, I am trying to write a function that calculate the factorial of a given number and also replace the fourth element. I expect when the code above is run, it should produce 6GeXmanX but instead i am getting NaNXermXny

function Recursion(num) {
  
  if (num=== 0 || num===1){
    return 1;
  }
  result= Recursion(num-1)*num;
  
  results = result + 'Germany'
  const str = results.split('')
  const nth = 4
  var replaceWith = 'X'
  for (var i = nth-1; i < str.length-1; i+=nth){
    str[i]= replaceWith;
    
    
  }
  //y = (results.join(""))
  return (str.join(""));
  
  }
  


  // code goes here  
   
// keep this function call here 
console.log(Recursion(3));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First, you need to split the factorial function into a separate function.

Second, in the for condition, the i should be i < str.length not i < str.length - 1 as it will not iterate over the last letter.

function factorial(num) {
  
  if (num=== 0 || num===1){
    return 1;
  }
  return  factorial(num-1)*num;
  
}
  
  
function func(num) {
  let results = factorial(num) + 'Germany'
  const str = results.split('')
  const nth = 4
  var replaceWith = 'X'
  for (var i = nth-1; i < str.length; i+=nth){
    str[i]= replaceWith;
  }
  //y = (results.join(""))
  return (str.join(""));
  
  }
  


  // code goes here  
   
// keep this function call here 
console.log(func(3));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading