Javascript: recursive function fails to return existing value

I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key.

The issue I am facing is that although the loop stops correctly when it finds a match, it only returns the value of the first key (index 0) in the array. For all subsequent keys, it returns 'undefined' instead.

Where did I go wrong? The following code demonstrates the problem:

function loop(arr, i) {
  var i = i||0;
  if (/i/gim.test(arr[i])) {
    console.log("key value is now: " + arr[i]);
    return arr[i]; // returning key value
  }
  
  console.log("key value: " + arr[i]); // test key value

  i+=1; // update index

  loop(arr, i); // call function with updated index
}

console.log(loop(["I", "am", "lost"]));
// Output:
// "key value is now: I"
// "I"

console.log(loop(["am", "I", "lost"])); 
// Output:
// "key value: am" 
// "key value is now: I"
// undefined

Answer №1

Make sure to always return the result from the recursive function call,


// recall with updated parameters
return recursion(arr, index); 
}

When you make the final call to the function recursion, it will return a value. However, all the previous calls to the same function without a return statement will result in the output being undefined. Therefore, ultimately you may end up with an output of undefined.

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

Securely Upload Files with JavaScript

Are there any methods to utilize javascript or ajax for encrypting file uploads securely? If so, could you provide a sample code snippet or direct me to a functional example? ...

What is the best way to trigger a function once another one has finished executing?

After opening the modal, I am creating some functions. The RefreshBirths() function requires the motherId and fatherId which are obtained from the getDictionaryMother() and getDictionaryFather() functions (these display my mothers and fathers on the page s ...

Steps to halt webkit animation within a div located inside a circle:

I have a series of nested circle divs, and I want to give them a pulse animation. The issue is that the text container is within one of these circles, causing the animation to apply to the text as well. I am unable to move the text container due to potenti ...

The auto complete feature seems to be malfunctioning as an error message is being displayed stating that iElement.autocomplete is not

I am currently attempting to create an auto complete feature for a search text box using Angularjs. However, I am encountering an error stating that iElement.autocomplete is not a function. Here is the code snippet: <body ng-controller='Friend ...

What steps should I take to transition from a class to a function in this scenario?

I am struggling to make the following code work properly. Every attempt I have made has resulted in issues with the event. import React from 'react' import YouTube from 'react-youtube'; export default class youtube extends React.Comp ...

Communication between AngularJS directives and controllers occur when a function is called upon a change

I have developed a unique custom directive which is defined as: <div class="col-md-6"> {{templateMapping[colProp].SheetPointer}} <select class="form-control" ng-model="selectedColumn" ng-change="changeMapping()" ng ...

What is the definition of a type that has the potential to encompass any subtree within an object through recursive processes?

Consider the data structure below: const data = { animilia: { chordata: { mammalia: { carnivora: { canidae: { canis: 'lupus', vulpes: 'vulpe' } } } } }, ...

Encountering a TypeError with DataTables and Tabledit

I've been attempting to integrate DataTables with Tabledit, but I keep encountering the error message "TypeError: Cannot set properties of undefined (setting 'nTf')". The number of tags also matches up. Interestingly, if I comment out the " ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

Custom-designed background featuring unique styles

I have implemented the following code to create a continuous running banner: <style> #myimage { position: fixed; left: 0%; width: 100%; bottom: 0%; background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bild ...

Show labels for data on a circular graph using angular-chart.js

I recently created a pie chart using angular-chart.js and it's functioning smoothly. However, I'm facing an issue with displaying the data value on each section of the pie chart. My attempt to use Chart.PieceLabel.js by adding the code snippet b ...

Is it necessary to implement clustering for each route in an Express.js application?

Currently, I am utilizing the cluster module to fork my application within my index.js, which serves as the primary file in the root directory of my website. My application consists of numerous routes. Should I incorporate the cluster code to encapsulate a ...

Error occurred due to an unexpected end of JSON input following a pending promise

I am currently developing a data handler that requires downloading a file for parsing and processing within the handler. To handle this, I have implemented the file request within a promise and called it asynchronously from other methods. Including the h ...

The escape character appears to be misunderstood, causing an error due to an invalid escape sequence

When using the following syntax: executeJSCommand("location.href='StatusDetails.php?CHLD=1\&JNum=1024&JTitle=';"); An error occurs displaying: Invalid Escape Sequence ...

The cell text you are trying to access is beyond the allowed range

I am currently developing a shopping application, but I have encountered a problem. Up to this point, I have been parsing JSON data and creating tableview cells. However, I am facing an issue where it is showing an 'index out of range' error: ov ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Issue encountered while installing npm via command line

Currently in the process of installing node on my Mac and encountering an error. I downloaded Node from the official website and executed the package, but I am still facing issues. Can anyone advise me on why this error is occurring when I attempt to run ...

"Implementing ASP.NET MVC4 with Razor: Dynamically filtering a dropdown list based on the selected value from another dropdown

Currently, I am facing a challenge where I need to filter the options of a dropdown list based on the value selected from another dropdown. Within my database, there are tables containing all countries and all cities in the world, with a foreign key linkin ...

ReactJS mixes up fetch URLs with another fetch_WRONG_FETCH

I have a fetch function in my Home component: export default function Home() { const { rootUrl } = useContext(UserContext); useEffect(() => { fetch(`${rootUrl}/api/products/featuredProducts`) .then((result) => result.json()) .then ...

Tips for inserting my array object into a Material UI table

Trying to populate a Material UI table with data from an array that I have. The structure of my array is sourced from a file that I imported using React Papa Parse 3. https://i.stack.imgur.com/Xw1wd.png I am working on integrating the data into the follo ...