What term is used to describe this in recursion?

I am trying to understand the concept of reversing a linked list and I stumbled upon a peculiar scenario in which a recursive function doesn't "return" but instead just calls itself. It seems that the function processes data backwards after the recursive call. I am curious to know if anyone is familiar with what this phenomenon is called or how it operates. Does it happen simultaneously? I highly doubt it. Is it merely a quirk of recursive functions to process data in reverse after the return statement executes at the top or right before it? It's a strange question, so here is an example...

function wow(cool) {
    if(cool === 10) return;
    cool += 1;
    console.log(cool);
    wow(cool);
    console.log(cool);
}

wow(0);

The real question is, when does the second console.log occur?

Answer №1

In the scenario provided below, it is evident that all the previously functions are executed before the subsequently functions. This sequence occurs because the stack must first complete its downward traversal before moving back up the stack in a reverse direction.

class Processor { previously(data){} subsequently(data){} }

const runner = (processor, start = 0, max = 10) => {
  if (start >= max) return;
  processor.previously(start);
  runner(processor, start + 1, max);
  processor.subsequently(start);
}

class MyProcessor extends Processor {
  previously(data) { console.log(`PREVIOUSLY : ${data}`); }
  subsequently(data) { console.log(`SUBSEQUENTLY  : ${data}`); }
}

runner(new MyProcessor(), 0, 10);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Answer №2

To better understand, it is important to note that each time the function is called recursively, a unique cool variable is created. This variable is not shared across all function executions, but rather each call generates its own instance of the variable. When the += 1 operation is performed, only that specific variable is modified while previous instances remain unchanged.

In the given example, the initial call establishes the variable with a value of 0 (as passed to it), which increments to 1 and remains constant thereafter.

Subsequent recursive calls create new instances of the cool variable, each starting with a value of 1, incrementing to 2, and then remaining static.

Each iteration of cool exists within its own "box", illustrating a series of nested contexts during execution.

For simplicity, the function is limited to run until 3 for easier tracking:

function wow(cool) {
    if(cool === 3) return;
    cool += 1;
    console.log(cool);
    wow(cool);
    console.log(cool);
}

wow(0);

The following outlines the sequential execution contexts, with each box representing a distinct context. Execution proceeds from top to bottom:

+----------------------------------------------+
| cool = 0                                     |
| cool += 1 // = 1                             |
| console.log(cool) // 1                       |
|   +--------------------------------------+   |
|   | cool = 1                             |   |
|   | cool += 1 // = 2                     |   |
|   | console.log(cool) // 2               |   |
|   |   +------------------------------+   |   |
|   |   | cool = 2                     |   |   |
|   |   | cool += 1 // = 3             |   |   |
|   |   | console.log(cool) // 3       |   |   |
|   |   |   +-----------------------+  |   |   |
|   |   |   | cool = 3              |  |   |   |
|   |   |   | if (cool == 3) return |  |   |   |
|   |   |   +-----------------------+  |   |   |
|   |   | console.log(cool) // 3       |   |   |
|   |   +------------------------------+   |   |
|   | console.log(cool) // 2               |   |
|   +--------------------------------------+   |
| console.log(cool) // 1                       |
+----------------------------------------------+

It's evident that each instance of cool exists within its own context, independent from variables in deeper nested contexts.

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

What is the best way to include the title "addmoves" to the server using AngularJS?

https://i.sstatic.net/yR2fk.png Furthermore, I am looking to include a button that allows users to add additional movies. The goal is to input multiple sets of data simultaneously, such as: newMovies = [ { movieName:"", director:"", release ...

Struggle arising from the clash between a customized image service and the built-in image element

Dealing with a custom Angular service called Image, I realized that using this name poses a problem as it clashes with Javascript's native Image element constructor, also named Image. This conflict arises when attempting to utilize both the custom Im ...

What is the best method for designing a custom mask for the jQuery Masked Input Plugin that accommodates alphanumeric characters, spaces, and accented

Looking for a way to make a custom mask in jQuery Masked Input Plugin that allows alphanumeric characters, spaces, and accented characters? This is what I currently have: $.mask.definitions["A"] = "[a-zA-Z0-9 ]"; $("#input").mask("A?AAAAAAA"); However, ...

Do we really need to implement ajax in this code snippet?

In my scenario, I have two JSP files named test1.jsp and test2.jsp. The flow of my program goes like this: I need to retrieve data from a textbox in test1.jsp, but the Ajax call is initiated from a different page. My objective is to receive the controller ...

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

Configure environment variables for either grunt or grunt-exec

Attempting to utilize grunt-exec for executing a javascript test runner while passing in a deployed link variable. This is being done by initializing an environment variable grunt.option('link') with the help of exec:setLink. Within my test_runn ...

Dynamic web page updates from server using an Ajax request

I have a JavaScript client application and an Express.js server. I am looking to update a page on my server with information sent through an AJAX call from my client application. I need the page to be updated in real-time. Here is the code snippet in my ...

Tips for incorporating conditions when updating data in MongoDB

I am looking for assistance with updating the secondary phone number in the code below. I want to update it only if a 10-digit number is passed from the web form; otherwise, I would like to use the already inserted phone number during the insert operation. ...

Finding and removing the replicated keys within a JSON array while also retrieving the corresponding JSON path

I have a JSON object that looks like this: {"response":{"result":{"Leads":{"row":[{"LEADID":"849730000000063017","SMOWNERID":"849730000000061001"},{"LEADID":"849730000000063015","SMOWNERID":"849730000000061001","HIII":"hello"},{"LEADID":"84973000000006 ...

Guide on sending a JSON response from an API endpoint in Next.js

As I work on developing a small REST API for a Next.js application, I encountered an interesting issue. Initially, when I placed my route.ts file in the directory structure rootDir -> app -> api -> hello -> route.ts with the following code snip ...

What is the process for creating an if statement for product activation?

<form method="get" formenctype="text/plain" action="https://app.cryptolens.io/api/key/Activate" > <input type="text" maxlength="23" size="80" name="Key" placeholder="XXXXX-XXXXX-XXXXX-XXXXX" /> <input type="hidden" name="toke ...

Is there a way to prevent the letters from moving when I hover over them?

What occurs when the numbers are hovered over: https://gyazo.com/20b6426d435551c5ee238241d3f96b4d Whenever I hover over the pagination numbers, they shift to the right, and I am unsure of what mistake I made in my code that's causing this. Below, I ...

Top method for creating a checkbox filter to toggle the display of elements depending on various data-* attributes

I am currently working on creating a checkbox filter that will display or hide elements based on multiple data attributes assigned to those elements. Despite my attempts, I have not been able to achieve the desired filtering outcome. You can view a basic ...

Limiting page entry with passport.js and express middleware

My server is set up to authenticate user login. I have successfully redirected users to the success page after authentication (and back to the login page if it fails). However, I am facing an issue with using my own express middleware to restrict access fo ...

Is it possible to have animations play in reverse once they have completed running?

Hi there! I'm currently tinkering with the transitioning animations for my navigation button. I've successfully implemented the opening animation where the three bars morph into a single line and the menu slides out. Now, I'm looking to crea ...

Can you explain the meaning of this AJAX code snippet?

I've been researching online for information, but I'm struggling to find any details about the AJAX code snippet that I'm using: function getEmployeeFilterOptions(){ var opts = []; $checkboxes.each(function(){ if(this.checke ...

Having issues making div elements with javascript

I am having trouble generating new divs when a specific div is clicked. Despite my efforts, nothing seems to be happening and the console isn't showing any errors. I've searched online for solutions but haven't found anything that addresses ...

Stopping the page from scrolling back to the top when an asynchronous update occurs in Angular

Once the asynchronous request is complete, I dynamically add a new element to the top with this code snippet: Array.prototype.unshift.apply(scope.conversation, conversation.data.message); The issue arises when the added element causes the scroll position ...

What is the best way to deliver an HTTP request from the controller to my Ajax function?

Is there a way to send HTTP OK and error responses from the controller to my AJAX request? For example, using HttpStatusCode.OK and HttpStatusCode.BadRequest. When I inspect in my browser it shows impresion.js 304 not modified. $(document).ready(functi ...

How to position button components at the center in a NextJS application?

Incorporating a button within my nextjs page has been a challenge as I am striving to position it in the center of the page for optimal viewing on both PCs and mobile devices. Despite various attempts, the button remains fixed on the far left side of the p ...