The intricacies of JavaScript recursion explained thoroughly

I'm struggling to grasp how this recursion will function. Specifically, I can't seem to comprehend how the final console ('end'--) is being executed. Any guidance on the execution aspect would be greatly appreciated as I am having trouble understanding how it generates the output.

function foo(i) {
  if (i < 0)
    return;
  console.log('begin: ' + i);
  foo(i - 1);
  console.log('end: ' + i);
}

foo(3);

Answer №1

Understanding the process of this function's execution:

Let's break down what happens when you call upon this method and provide 3 as the argument:

foo(3);
 // Since (3<0) is false, the return is skipped
 // Display: 'begin: 3'
  //foo (2);
  // Due to (2<0), return is skipped;
  // Display: 'begin: 2'
    //foo(1);
      // As (1<0) is false, return is skipped;
      // Display: 'begin: 1'
      //foo(0);
        // Since (0<0) is false, return is skipped;
        // Display: 'begin: 0'
        //foo(-1);
        //(-1 < 0) is true!!! 
        //return undefined
      // Display: 'end: 0'
      //return undefined
    //Display: 'end: 1'
    //return undefined
  //Display: 'end: 2'
  //return undefined
//Display: 'end: 3'
<---return undefined

Here is the output that is generated:

begin: 3
begin: 2
begin: 1
begin: 0
end: 0
end: 1
end: 2
end: 3
undefined

Answer №2

Starting with the first iteration: when foo(3) is called, i is set to 3, then foo(2) is invoked with i=2, followed by i=1 and i=0. Subsequently, foo(-1) gets executed. At this point, the if condition evaluates to true, leading to a return in the call of foo(0), where console.log displays i=0. The cycle then continues with i=1, i=2, and finally i=3.

This results in the following sequence:


begin 3
begin 2
begin 1
begin 0
end 0
end 1
end 2
end 3

Answer №3

Upon calling foo(3), the following sequence is observed:

begin: 3
begin: 2
begin: 1
begin: 0
end: 0
end: 1
end: 2
end: 3

The inner workings of the code are as follows:

begin: 3
//foo gets called, foo(2)
//commencement of foo(2) function
begin: 2
//foo gets called, foo(1)
//commencement of foo(1) function
begin: 1
//foo gets called, foo(0)
//commencement of foo(0) function
begin: 0
//foo gets called, foo(-1)
//commencement of foo(-1) function
//condition in if statement evaluates to true, returning and terminating recursion
//execution returns to the foo(0) method, logging i
end: 0
//execution jumps back to the foo(1) method, logging i
end: 1
//execution jumps back to the foo(2) method, logging i
end: 2
//execution jumps back to the foo(3) method, logging i
end: 3

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 user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Pause the counter based on the data attribute containing multiple values

I have a collection of div elements, each with a unique data-attribute value. My goal is to display these values in the divs using JavaScript by incrementing a counter. const numbers = document.querySelectorAll(".number"); console.log(numbers); let c ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...

What is the best way to retrieve a collection of DOM elements in JSX?

I'm in need of rendering certain components only if a specific condition is met. To achieve this, I have written the following inside the render() method: return ( <div className={classes.root}> {registrationScreen && ( * ...

I am encountering a problem with the $invalid property in AngularJS

Hey there, I've got a coding dilemma involving three number inputs, which I will refer to as the first input, second input, and third input for clarity. Here's the setup: <div> <form name="formOpenMax"> <div clas ...

Experiencing a blank array when using filtering/search text in a Nodejs application with MongoDB

I am experimenting with search functionality in a MongoDB database using Node.js. However, my result array is always empty. I have shared my code here and would appreciate some assistance in identifying the issue. Whenever I perform a search, I end up with ...

React: the props appear to be undefined when they should actually have a value

I have a requirement for my props in the children class to be an array of Event objects. Prior to using it in App.js, I am checking if the array is empty like this: function App() { class Event { constructor(id, title, date){ this.id = id; ...

Can JavaScript be used to upload a file directly to memory for processing before transferring it to the server?

I'm exploring the idea of using a JavaScript encryption library (not Java) to encrypt a file before sending it to the server. Is it feasible to perform this process on the client-side and then upload the encrypted file using JavaScript, storing it in ...

Is there a way to include an item into a three.js environment during a mouse click event?

Is it possible to dynamically add a 3D object to a three.js scene after it has been initialized and the user triggers a click event? How can this be achieved within the existing code structure provided? You can find a prepared scene setup in this working ...

What is the best way to arrange the elements of an array based on a specified value?

Is there a way to develop a function that can organize an array of data based on the value of a specified field? Suppose the field consists of three numbers: 1, 2, 3. The idea is that upon providing a certain value to the function, it will rearrange the ta ...

WordPress CSS & JS files failing to enqueue properly

My attempt to integrate my CSS and JS files with WordPress has not been successful. Although my CSS works through the Custom CSS tab, this is not an ideal solution. Below is the code from my functions.php file for your reference. Can you help me troublesho ...

Refresh choices for the user interface selection menu

I've successfully mastered the art of redefining options for Webix ui.richselect/ui.combo. The technique involves: richselect.getList().clearAll(); richselect.getList().parse(options_data) Now, I'm facing a challenge with changing options fo ...

Error message: "The jQuery function is unable to recognize the

I am working with a JSON object that looks like this: {"a":"111","b":"7"} In addition, I have a select box with options for "a" and "b". I want the selected value to display either "111" or "7" from the JSON object. Here is the jQuery code I wrote for t ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build. Fe ...

Received an unexpected GET request while attempting to modify an HTML attribute

After clicking a button in my HTML file, a function is called from a separate file. Here is the code for that function: function getRandomVideoLink(){ //AJAX request to /random-video console.log("ajax request"); var xhttp = new XMLHttpRequest( ...

Develop a versatile JavaScript or jQuery script that automatically sets the focus on the first input field within a div or tag when the user clicks on it

I am currently working on creating a data entry form using a table layout. The form has two columns - the first column for input titles and the second column mostly for input tags. I styled the inputs in the second column to appear transparent with no bord ...

What are the available search options in the MarkLogic Search API to limit keyword searches from including specified values within JSON properties?

Is there a way to limit the MarkLogic search API keyword search so it does not include specific JSON property values? For example, can I search for keyword 'x' in all properties of JSON documents except for those with values of 'p', &ap ...

Creating a legitimate svg element using javascript

While working with SVG, I had an issue where I added a <rect> element directly into the svg using html, and then created a new element (without namespace) <circle> with javascript. However, the <circle> element did not display in the svg ...

Creating a table and populating its cells with values all within the confines of a single function

This section of code aims to create 3 arrays by extracting values inputted by the user from a popup menu in the HTML file. These values are then utilized to populate the table displayed below. var arrM = new Array; var arrT = new Array; var ar ...