Home > Software engineering >  Is this good practice to do in a function? calling a same function inside it's own function
Is this good practice to do in a function? calling a same function inside it's own function

Time:12-11

function takaAnumber() {
  startHealth = parseInt(prompt("give a positive number "));
//here i am calling the same function inside the if()block if the input is not a number or lesser than 0 is this a good practice? 
  if (isNaN(startHealth) || startHealth <= 0) {
    takaAnumber();
  }
  // checkItsnumber();
  playerHealth = startHealth;
  monsterHealth = startHealth;
  adjustHealthBars(startHealth);
}

I am trying get a number as an input, by calling a function. Inside the function the I have wrote a if() statement to check its a number if isn't it will call the function again. My question is it safe(good practice) to call a function inside it's own function in a large project code.

CodePudding user response:

Your approach needs a return statement, because if the function returns, it goes on with the code of the calling function.

function takaAnumber() {
    const startHealth = parseInt(prompt("give a positive number ")); // declare variables
    if (isNaN(startHealth) || startHealth <= 0) {
        return takaAnumber();
    }
    // other code
}
  • Related