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

Attempting to transmit information using Ajax to an object-oriented programming (OOP) class

Trying to send data with username, password, etc from an HTML form -> Ajax -> Instance -> OOP class file. Questioning the approach... Begins with the form on index.php <!-- Form for signing up --> <form method="post"> <div ...

Having issues updating table with Javascript after form submit in IE and Edge browsers

My current setup involves using Contact Form 7 in Wordpress to store data in a MySQL Database with Submit-Form. Now, I am working on reloading a table containing this data after the form submission. Here is the script I am currently using: /* FORM RELOAD ...

Capable of displaying array in console, however unable to iterate through its elements

Encountering an issue while working with React and fetching data from a JSON API. Initially, everything was functioning smoothly until it came to displaying the data. Strangely, I could see the data being logged in the console. Here is what the console lo ...

Nuxt: Encountered an unexpected < symbol

https://i.sstatic.net/MbM9f.png I've been working on a nuxt project where I'm currently in the process of creating a map component using Google Maps with the help of the plugin https://www.npmjs.com/package/vue2-google-maps. After installing the ...

Node.js redirection techniques

Node JS is still very new to me and I'm having trouble redirecting buttons to another page. Every time I attempt to redirect, I receive a "cannot GET /(the page that I am trying to redirect to)" error message. The code snippet I'm using for redir ...

Ways to ensure that the $http.post api call waits for the response to be fully prepared

Below is the JavaScript code that I am using. When I click the button, it calls the function btnInitiateAPICall() which makes the first API call to get the number of users. However, my code does not wait for the first API call to finish before moving on ...

Is there something I'm overlooking when it comes to vue router transitions?

I am attempting to implement a smooth transition between my Vue components with the following code: <template> <div id="app"> <router-link to="/">Go to home</router-link> <router-link to="Register">Go to register< ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

What might be preventing combineLatest from executing?

Currently, I am attempting to run a block of code utilizing the combineLatest function. Within my translation library, there exists an RXJS Observable that is returned. Imported as individual functions are combineLatest, map, and tap. combineLatest(this. ...

Designate a Cookie for individual users

Currently, I am in the process of building a straightforward Wordpress website that aims to monitor a user's order using a specific Cookie. Although most of the functionalities are already implemented, an unexpected issue has surfaced. Upon logging i ...

Getting started with `sessionStorage` in a React application

Currently, I am attempting to save an item in sessionStorage prior to rendering. The code snippet I have looks like this: componentWillMount() { sessionStorage.setItem("isUserLogged", false); } However, I encountered an error stating th ...

Create fluidly changing pictures within varying div elements

Hello there! I have a form consisting of four divs, each representing a full page to be printed like the one shown here: I've successfully created all the controls using AJAX without any issues. Then, I load the images with another AJAX call, and bel ...

Finding distinct values in a multidimensional array using JavaScript

When working with JavaScript, I created a multidimensional array using the following code: result.each(function(i, element){ init.push({ label : $(this).data('label'), value : $(this).val(), }); }); The resulting array in ...

Node.js and TestCafe encountered a critical error: Inefficient mark-compacts were performed near the heap limit, resulting in an allocation failure. The JavaScript heap ran

While executing my test scripts in Node v14.6.0, I encountered the following problem. Here are some of the options I've tried: I attempted to increase the Node Heap Size but unfortunately had no success: export NODE_OPTIONS=--max_old_space_size=4096 ...

What are some ways to implement smooth scrolling when a navigation link is clicked?

I have a total of 3 links in my navigation bar and every time they are clicked, I want the page to smoothly scroll down to their designated section on the webpage. Although I have already set up the anchors, I lack experience in scripting to create the smo ...

What are some ways to improve performance in JavaScript?

Can you help me determine which approach would be more efficient - using native functions of the language that involve 2 iterations or a simple for loop? The goal is to locate the index in an array of objects where the property filterId matches a specific ...

What is the best way to align my clip-path's text with the center of the viewport and ensure that all of the clip-path's text is visible?

Check out my React component demo: https://codesandbox.io/s/epic-brown-osiq1. I am currently utilizing the values of viewBox, getBBox, and getBoundingClientRect() to perform calculations for positioning elements. At the moment, I have hardcoded some values ...

Obtaining distinct form control values for replicated form fields with Angular

Issue with Dynamic Form Duplicates: I am currently working with a reactive form that has two fields - name and value. There is an add button that duplicates the form by copying these fields. The challenge I am facing is with updating the values of the dup ...

Retrieve data from a Rails controller using Ajax

Seeking assistance and insight for a coding dilemma I'm facing. In my Rails application, I have a controller named get_songs that retrieves a hash of songs belonging to the currently logged-in user. What I'm trying to achieve is to fetch this dat ...

Is the detailedDescription missing from the JSON-LD schema crawl?

I am currently utilizing the Google Knowledge Graph Search (kgsearch) API to retrieve Schemas from schema.org. However, I am encountering an issue where some nested elements are not being recognized as JSON or I may be overlooking something... url = "http ...