What could be the reason for getting undefined when printing console.log(fibonacci(3))?

let array = [0, 1, 1];

const fibonacciSequence = (number) => {
    if (number < 2) {
        return array[number];
    } else if (number == 2) {
        console.log(array.length-1);
        console.log((array[array.length-1]));
        // return (array[array.length - 1]);
        return (array[array.length-1]); // why does this return statement give undefined???
    }
    else {
        array.push(array[array.length - 1] + array[array.length - 2]);
        fibonacciSequence(number - 1);
    }
};

console.log(fibonacciSequence(3));

Expected result: 2..

Answer №1

Revise your code like this:

let sequence = [0, 1, 1];

const fibonacciGenerator = (num) => {
    if (num < 2) {
        return sequence[num];
    } else if (num == 2) {
        console.log(sequence.length-1);
        console.log((sequence[sequence.length-1]));
        // return (sequence[sequence.length - 1]);
        return (sequence[sequence.length-1]); // why does this return statement come back as undefined???
    }
    else {
        sequence.push(sequence[sequence.length - 1] + sequence[sequence.length - 2]);
        return fibonacciGenerator(num - 1);
    }
};

console.log(fibonacciGenerator(4));

You forgot to include a return before the recursive call of fibonacci(n - 1) inside the else block.

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

Event follows activation of trigger click

I've already gone through this post on Stack Overflow about triggering an action after a click event, but none of the solutions I've tried so far have worked. Let's say I have a menu on my webpage like this: <ul class="nav nav-tabs"&g ...

Guide on transferring information from .ejs file to .js file?

When sending data to a .ejs file using the res.render() method, how can we pass the same data to a .js file if that .ejs file includes a .js file in a script tag? // Server file snippet app.get('/student/data_structures/mock_test_1', (req, res) = ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...

Why am I getting the error in react-dom.development.js related to my index.js file?

Upon checking the console, the following message is displayed: react-dom.development.js:86 Warning: ReactDOM.render is no longer supported in React 18. Please use createRoot instead. Until you transition to the new API, your application will behave as if i ...

Guide to implementing hapi-auth-jwt2 authorization on a specific route within hapi.js?

I am facing an issue with using an access token in hapi.js. I am struggling to comprehend how to utilize this token for authentication purposes. Currently, I am referring to the article on dwyl/hapi-auth-jwt2. My database setup involves mongodb. However, I ...

Conceal any elements designated by a particular class and reveal them based on their corresponding ID

I have utilized jQuery's hide() function to initially hide all elements of a specific class when the page loads. My goal is to make individual elements visible again based on their unique IDs when a corresponding link is clicked. In total, there are ...

Ways to invoke a function within a React Material-UI component

Currently, I am in the process of setting up a chat system that allows users to add emojis. To achieve this feature, I have devised a function that produces a component containing both text and an image. Here is the function I have implemented: test: fu ...

How do the scopes of a controller and a directive's controller differ from each other?

Can you explain the difference between a controller and a directive's controller in terms of scope? I'm struggling to grasp the distinction and whether it's necessary to create controllers within the DDO for my directives. In the code snipp ...

Tips for navigating to an element with Nightwatch

I am currently using nightwatch for end-to-end testing of my application. One of the tests is failing because it seems unable to scroll to the element that needs to be tested. I am wondering if scrolling is necessary, or if there is another workaround. Her ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

The error message that you are seeing is indicating that the `contracts` property of `this.state

Despite having encountered this issue before, I am still struggling to find a solution. The code snippet for fetching data is as follows: async componentDidMount(){ try { const res = await fetch('https://example.com/data.json'); ...

What is the best way to create a menu in JavaScript that includes a variable declaration?

Here is the menu I've created: <a id="page1" href="" onclick="var = page1">Home</a> <a id="page2" href="" >About us</a> <a id="page3" href="" >Services</a> <a id="page4" href="" >Partners</a> <a ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

Assign the value from a drop-down menu to an SQL variable dynamically without the need for a submit button

I am trying to retrieve the value of the selected item in a drop-down menu populated from an SQL database. This value is essential for me to formulate the SQL statement required to access a specific record. The drop-down menu has already been populated. S ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

The functionality of Layout.tsx is inconsistent across various pages

I'm having trouble with the console.log() code to display the page path only showing up in the "pages.tsx" file (src/app/pages.tsx) and not appearing in the console for other files located in (src/page/Login). Here is the code from layout.tsx: ' ...