Is it considered best practice to call the same function within itself in a function?

function takeANumber() {
  let startHealth = parseInt(prompt("Please enter a positive number:"));
// I am recursively calling the same function within an if block to ensure that the input is a valid number greater than zero. Is this considered good practice?
  if (isNaN(startHealth) || startHealth <= 0) {
    takeANumber();
  }
  // checkIfNumber();
  let playerHealth = startHealth;
  let monsterHealth = startHealth;
  adjustHealthBars(startHealth);
}

I am attempting to receive a positive number through a function call. Within the function, I have included an if statement to verify if the input is numeric. If it's not, the function is called again. My concern is whether it is safe or considered good practice to call a function within itself in a larger project codebase.

Answer №1

Your strategy requires the inclusion of a return statement, as when the function returns, it proceeds with the code in the calling function.

function getANumber() {
    const startingValue = parseInt(prompt("Please enter a positive number")); // defining variables
    if (isNaN(startingValue) || startingValue <= 0) {
        return getANumber();
    }
    // additional code
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic sidebar menu with clickable submenus through jQuery and CSS for a user-friendly experience

<div id="sidebar" class="sidebar"> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;"> <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: a ...

The vue-pdf is having trouble loading all pages due to an "undefined property" issue

I am currently utilizing the following technologies: Vue.js, vue-route, Vuetify, Firebase (with a database) and vue-pdf The issue I am facing involves attempting to load all pdf pages using "vue-pdf" plugin. However, when trying to read the pdf, I encoun ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

What is the root cause behind the recurring appearance of this line in Angular/D3.js?

I recently came across an excellent tutorial on integrating the D3.js library with AngularJS by following this link: . The guide provided has been extremely helpful in getting me started (big thanks to Brian!) However, I'm eager to delve deeper into ...

Ensure exclusive access to variables for sequential updates in jQuery or JavaScript

I am currently developing a series of small functions in jQuery aimed at tracking how long it takes for a user to complete a form. The form consists of various input types and 'continue' buttons located within the form itself. Below are some sa ...

Move each four-character IT value to a new line

const maxNumLength = 4; event = jQuery.Event("keypress") event.which = 13 $('#input').on('input focus keydown keyup', function() { const inputValue = $(this).val(); const linesArray = inputValue.split(/(&bsol ...

The exportAs attribute is not specified as "ngForm" for any directive

Encountered an error while attempting to test the LoginComponent PhantomJS 2.1.1 (Linux 0.0.0): Executed 3 of 55 (1 FAILED) (0 secs / 0.307 secs) PhantomJS 2.1.1 (Linux 0.0.0) LoginComponent should create FAILED Failed: Uncaught (in promise): Error: Templ ...

Is the vertex count of a Geometry in Three.js increased when it is converted to a BufferGeometry?

Recently, I've been experimenting with the fromGeometry method to convert regular Geometry objects into BufferGeometry objects. To my surprise, I noticed that the number of vertices increases during this conversion process. For instance, consider the ...

What is the best way to pass a function along with its state to utilize useContext in React

Currently attempting to grasp the concept of using react hooks. I have implemented createContext and am looking to pass both state and a function to other components, but could use some guidance on how to achieve this. I'm also questioning if it is ev ...

The art of selecting elements and attaching event listeners in a React environment

Currently, I am working on my portfolio website using Gatsby. The layout includes a sidebar on the left with navigational links (Home, About, Work, etc.), and the main content is displayed as one long strip of sections on the right. When a user clicks on a ...

The second attempt at an AJAX call is unsuccessful

I am currently developing a form that displays database results based on two entries: Automarke (brand) and Modell (model). You can view the entries here. The Modell dropdown dynamically changes based on the selected Automarke. Here is the code snippet I ...

How to make Sails.js package accessible across all modules

Recently, I have been using Sails frequently and came across a common practice question. Whenever I need to use a specific NPM package multiple times in a project, I typically include it in my config/bootstrap.js file like this: module.exports.bootstrap = ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

Text transitions in a gentle fade effect, appearing and disappearing with each change

I want to create a smooth fade in and out effect for the text within a div when it changes or hides. After researching on Google and Stack Overflow, I found that most solutions involve adding a 'hide' CSS class and toggling it with a custom func ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

What is the purpose of utilizing "({ })" syntax in jQuery?

What is the purpose of using ({ }) in this context? Does it involve delegation? Can you explain the significance of utilizing this syntax? What elements are being encapsulated within it? For instance: $.ajaxSetup ({ // <-- HERE error: fError, ...

What is the best way to organize two separate arrays based on a single shared variable?

I have two separate arrays containing information. One array includes the title of each national park and other related data, while the second array consists of alerts from the entire NPS system. The common factor between these arrays is the parkCode. How ...

Transform the MUI Typescript Autocomplete component to output singular values of a specific property rather than a complete object

When utilizing MUI Autocomplete, the generic value specified in onChange / value is determined by the interface of the object set in the options property. For instance, consider an autocomplete with the following setup: <Autocomplete options={top ...

What steps should I take to resolve the issue with this error message: Error: listen EADDRINUSE

How can I resolve the following issue? system: gulp npm windows issue: ... Oh no. Encountered error listen EADDRINUSE 127.0.0.1:35729 ... Error: listen EADDRINUSE 127.0.0.1:35729 at Object._errnoException (util.js:1021:11) at _exce ...