Implementing closure within a recursive function allows for better control

One of my functions is designed to take a parameter and print the last number in the Fibonacci Series. For example, if the parameter is 3, it would return 2 as the series progresses like 1, 1, 2.

function recursionFib(num){
            if(num==0) return 0;
            if(num==1) return 1;
            return recursionFib(num-1)+recursionFib(num-2);
        }

Now, I am interested in implementing closure within this function so that I can display the entire Fibonacci series instead of just the last number.

Answer №1

If you are implementing recursion, it is important to have a print function that maintains the pattern.

function displayAndContinue(value) {
    console.log(value);
    return value;
}

You can incorporate this function in your return statements to both print and return the value. For example:

function fibonacciRecursion(num){
    if(num==0) return displayAndContinue(0);
    if(num==1) return displayAndContinue(1);
    return displayAndContinue(fibonacciRecursion(num-1)+fibonacciRecursion(num-2));
}

This approach will showcase the computation tree. If you only want to display the series, print the result of fibonacciRecursion(num-1) and then the total sum.

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

Autocomplete is failing to provide any results

I am experiencing an issue with the autocomplete script as it is not displaying any names under the input field. Below is the code snippet from my index file: <head> <html lang="en"> <meta charset="utf-8"> <meta na ...

Disregard Cloudflare's Automatic RocketLoader feature for certain JavaScript scripts

After extensive research and failed attempts, I am seeking help to disable Cloudflare Rocketloader for a specific JavaScript file on my WordPress website. Specifically, I need to exclude the Automatic Rocket Loader for a particular .js file. I attempted t ...

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

Exploring the internet with Internet Explorer is like navigating a jungle of if statements

I am facing an issue with my code that works well in Chrome, but encounters errors in IE. The if condition functions correctly in Chrome, however, in IE it seems like the first condition always gets executed despite the value of resData. Upon analysis thro ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

What exactly is the purpose of the QueryString function and how does it work

I recently took on the role of editor for a website that I did not create. One of the webpages contains a map feature, and I've been tasked with changing how the map loads initially on the webpage. As I review the JavaScript code, I'm unsure if ...

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

What is the reason for receiving the "Must provide query string" error when using the fetch API, but not when using cURL or Postman?

I've been attempting to integrate the graphbrainz library into a React app using the fetch API. No matter how I structure my request body, I keep encountering this error: BadRequestError: Must provide query string. at graphqlMiddleware (C:\U ...

Submitting forms using AJAX in Django

I am getting a 'Not Ajax' response every time I try to submit my form. There must be something small that I'm overlooking... class VideoLikeView(View): def post(self, request): if request.is_ajax(): message = 'Aj ...

Incorporate v-if to target a particular item within a v-for loop

On my Vue page, I have the following HTML code snippet: <div v-for="profile in lab.profiles" v-if="edit || profile.active" class="lab-tests-row-div" @mouseover=""> <div class="clickBox" :class="['clickBox-' + lab.id + ' ...

Obtain all the selection choices in a dropdown list using Selenium

Although I have come across similar questions, this one is distinct in its simplicity. Unlike other queries that involve iterating over options in a loop, my question revolves around the usage of the getOptions() method mentioned in Selenium documentation. ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

reasons why the keypress event may not be triggered

Hello there, I am trying to create a function that simulates pressing the 'tab' key. The function is supposed to restrict input within specific ranges and return the cursor to another range once the limit is reached. Additionally, if a user input ...

An issue has occurred: Cannot access the properties of an undefined object (specifically 'controls')

I encountered an error message stating "TypeError: Cannot read property 'controls' of undefined" in the code that I am not familiar with. My goal is to identify the source of this error. Below is the HTML code snippet from my webpage: <div ...

What is the best way to save the response data into an array outside of the current function in Node.js?

How can I efficiently store all the result data into an array called pImages? I am able to retrieve the results, but I believe using an async function would be more suitable. However, I am unsure of how to implement it. Any assistance would be greatly appr ...

Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json: { "pages" : [ { "name" : "home" ...

Implementing append operations in JavaScript without relying on the id attribute

Is there a way to specify the second div without assigning it an ID or using any attributes, and then perform an append operation inside it? For instance, indicating that the p element should be appended within the second div without relying on an ID or ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...