Having issues with the reverse function in JavaScript

Can anyone help me understand why my recursive string reversal function is returning undefined?

const reverse = (str) => {
  const looper = (str, index) => {
    if (index < 0) {
      return '';
    }
    return str[index] + looper(str, index - 1);
  };

  return looper(str, str.length - 1); // Added 'return' statement here
};

console.log(reverse('Hello World!'));

Answer №1

Make sure to include a return statement in your main function

const reverseString = function(str) {
    const recursiveReverse = function(str, index) {
        if(index < 0) {
            return '';
        }
        return str[index] + recursiveReverse(str, index - 1);
    };

    return recursiveReverse(str, str.length - 1);
};

console.log(reverseString('Lorem Ipsum!'));

Answer №2

Here is an alternative method using destructuring

const reversedString = ([firstChar,...remainingChars]) =>
  firstChar === undefined
    ? ''
    : reversedString(remainingChars) + firstChar

console.log (reversedString('hello world'))
// 'dlrow olleh'

console.log (reversedString(''))
// ''

Now let's optimize it with a tail call

const reversedString = ([firstChar,...remainingChars], callback = char => char) =>
  firstChar === undefined
    ? callback('')
    : reversedString(remainingChars, nextChar =>
        callback(nextChar + firstChar))

console.log(reversedString('hello world'))
// 'dlrow olleh'

console.log(reversedString(''))
// ''


Next, we'll attempt the same without using destructuring

const reversedString = characters =>
  characters.length === 0
    ? ''
    : reversedString(characters.slice(1)) + characters.slice(0, 1)

console.log(reversedString('hello world'))
// 'dlrow olleh'

console.log(reversedString(''))
// ''

Let's try implementing it with a tail call as well

const reversedString = (characters, callback = char => char) =>
  characters.length === 0
    ? callback('')
    : reversedString(characters.slice(1), nextChar =>
        callback(nextChar + characters.slice(0,1)))

console.log(reversedString('hello world'))
// 'dlrow olleh'

console.log(reversedString(''))
// ''

Some may prefer to use .substr instead of .slice and .concat instead of + – the choice is yours

const reversedString = (characters, callback = char => char) =>
  characters.length === 0
    ? callback('')
    : reversedString(characters.substr(1), nextChar =>
        callback(nextChar.concat(characters.substr(0,1))))

console.log(reversedString('hello world'))
// 'dlrow olleh'

console.log(reversedString(''))
// ''

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

Issue NG1006: Class has two conflicting decorators applied

I encountered an issue while compiling my project: PS C:\Users\hasna\Downloads\A La Marocaine git - Copie\ALaMarocaineFinal\frontend\src\app> ng serve Compiling @angular/forms : es2015 as esm2015 An unhandled exc ...

Is iterating through object with a hasOwnProperty validation necessary?

Is there any benefit to using hasOwnProperty in a loop when an object will always have properties? Take this scenario: const fruits = { banana: 15, kiwi: 10, pineapple: 6, } for (let key in fruits) { if (fruits.hasOwnProperty(key)) { ...

Using Response.Redirect within a Webmethod

I am facing an issue with the response.redirect command in my webmethod call. Here is a snippet of my code: HTML: <a onclick="proximaAula()">Next Lesson -></a> JS: function proximaAula() { var tipo = getParameterByName('t' ...

AngularJS: Updating data in controller but not reflecting in the HTML view

Within my AngularJS app, I've come across the following code: example.html <div> <p>{{name}}</p> </div> <div> <button ng-click="someFunction()"></button> </div> exa ...

The Impact of Speed and Performance on Generating Multiple HTML Templates using JavaScript Classes

Currently, I am in the process of developing a travel website using Ruby on Rails 4 which heavily relies on Javascript (or Coffeescript) for functionalities such as Google Maps and other APIs. The workflow involves making an initial call to the server, con ...

Issue with Axios code execution following `.then` statement

Recently diving into the world of react/nodejs/express/javascript, I encountered an interesting challenge: My goal is to retrieve a number, increment it by 1, use this new number (newFreshId) to create a new javascript object, and finally add this event t ...

Retrieve the HTML form field during an AJAX request

My task involves creating dynamic fields with labels based on user input. To clarify: I prompt the user to select a date range, and I want to generate label and input field for each date within that range. To achieve this, I implemented an AJAX function ...

CSS changes triggered by JQuery are ineffective

Having trouble modifying the CSS of a class in my HTML file. I've been struggling with this for quite some time and can't figure out what I'm doing wrong. (I've already attempted multiple versions, but nothing seems to work) Here' ...

Finding the value of a radio button dynamically created by jQuery

I am having an issue retrieving the value of a radio button that is generated using jQuery. I suspect there may be some problems with event handling. Below is my code: HTML <div id="divOption1"></div> The jQuery script to generate t ...

Having trouble transferring data between Vue.JS components

Wondering how to pass data from the parent component (Home route) to the child component (playlist route) using props? Encountering a "TypeError: Cannot read property 'length' of undefined" error in the child component? These two components are c ...

Enhancement from the original JavaScript class framework created by John Resig

Greetings everyone, Lately, I've been on the lookout for a straightforward JavaScript class framework that focuses solely on basic inheritance. After some research, I stumbled upon John Resig's sample framework shared on his blog, and it seems t ...

Requiring a condition for each element in an array which is part of an object

Let's discuss a scenario where I have to decide whether to display a block based on a certain condition. Here is an example array structure: const data = [ { name: "item1" , values : [0,0,0,0,0]}, { name: "item2" , values : [0,0,0,0,0]}, { nam ...

Experiencing an issue with Angular 14 when trying to install apollo-angular as

For the past two days, I've been attempting to set up apollo on an Angular application. Unfortunately, I keep encountering the following error: The package <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea8b9a85868685c78b8 ...

JavaScript counter to monitor the number of requests made to the Open Weather Map API

Currently, I am utilizing the Open Weather Map's free API which allows me to make 1000 API calls per day through their One Call API. However, there is no built-in feature for tracking these calls in the Open Weather Map platform. To address this issue ...

jQuery with various onClick event listeners

I have successfully implemented a calendar feature with a "More" button on each day to display additional events if there are more than three. However, I am facing an issue where clicking the button triggers the dropdown for all days instead of just the se ...

Tips for reactivating a disabled mouseover event in jQuery

I created an input field with a hover effect that reveals an edit button upon mouseover. After clicking the button, I disabled the hover event using jQuery. However, I am unable to re-enable this hover event by clicking the same button. Here is the code s ...

Call a PHP function within a functions file using a JavaScript function

Seeking a way to navigate between PHP and JavaScript worlds with confidence. There's a collection of PHP functions stored neatly in custom_functions.php waiting to be called from JavaScript. As I delve into the realm of JavaScript and jQuery, my fam ...

Axios consistently responds with the error message "[AxiosError: Request unsuccessful with status code 400]."

When an error occurs in the catch block, Axios does not return errors in JSON format. Sign-up Page const handleSignup = async () => { try { setIsLoading(true) const res = await axios({ url: 'http://10.0.2.2:8080/signup&ap ...

Selecting JavaScript Libraries During the Development of a Web Application

Transitioning from PHP & Java/Android development to web app development can feel overwhelming, especially with the abundance of Javascript Frameworks available. Check out this comparison of popular JavaScript frameworks View a list of the top JavaSc ...

Adding options to a select element in AngularJs is a simple

When working with AngularJS and a select options collection, I encountered an issue. Everything worked fine when I manually added option tags in the HTML, but it didn't work when trying to add items from Angular. This is my code: <div ng-controll ...