What is the reason for the function to return 'undefined' when the variable already holds the accurate result?

I have created a function that aims to calculate the digital root of a given number.

Despite my efforts, I am encountering an issue where this function consistently returns undefined, even though the variable does hold the correct result.

Can you help me identify where I might be going wrong?

    function findDigitalRoot(number: number): number {
        let sum: number = 0;
        while (number > 0) {
            sum += number % 10
            number = Math.floor(number / 10)
        }
        if (sum >= 10) {
            findDigitalRoot(sum)
        } else {
            alert(sum)  //  sum=6
            return sum  //  undefined
        }
    }

    alert(findDigitalRoot(942))  //  undefined

Answer №1

You are missing a return statement for the condition if(s>=10)

function calculateRoot(number){
    let sum = 0;
    while(number>0){
        sum+=number%10
        number = Math.floor(number /10)
    }
    if (sum>=10){
        return calculateRoot(sum)
    } 
    else{
        alert(sum)//sum=6
        return sum//undefined
    }
    
}
alert(calculateRoot(942))//undefined

Answer №2

Valid reasoning, however only return when the value of s is greater than 10. Appreciate it.

if (s>10){
      return fibNumber(s);
    }

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

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

The parameters passed in an axios get request are not carried over to a create request

Exploring the capabilities of the YouTube API with ReactJS While working with the YouTube API, I came across the create method in axios. However, I faced an issue where the params were getting overwritten. What am I missing here? I have a file named yout ...

Generate types based on properties of a nested interface dynamically

Consider the setup provided: enum FormGroups { customer = 'customer', address = 'address', } interface Customer { 'firstName': string; } interface Address { 'street': string; } interface SomeFormEvent { ...

Using JavaScript's `Map` function instead of a traditional `for`

My dataset consists of a csv file containing 5000 rows, with each row having thirty fields representing measurements of different chemical elements. I aim to parse and visualize this data using D3js. Upon reading the file, I obtain an array of length 5000 ...

The process of importing does not produce the anticipated System.register

I'm a beginner with Angular2, currently learning and practicing by doing exercises. I am enrolled in a Udemy course and comparing my exercise progress with the instructions provided. Here is a snippet from my app.component.ts file: import {Component ...

Single-select components in React Native

I am currently working on implementing a simple single selectable item feature, illustrated in the image provided below. https://i.stack.imgur.com/U2rJd.png At this moment, I have set up an array containing my data items and utilized the .map function to ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Analyzing npm directive

I have a script that handles data replacement in the database and I need to execute it using an npm command package.json "scripts": { "database": "node devData/database.js --delete & node devData/database.js --import" ...

Difficulty closing Modal Popup when multiple Modals are displayed simultaneously

I am facing a challenge with transitioning between modal screens When the button on the screen is clicked, Modal1 opens: $modal.open({ templateUrl: 'abc.html', controller: 'abcCtrl', size: 'lg', scope: $scope ...

Error Alert: missing property data in angular 5 type

I attempted to design an interface in interface.ts. The data consists of an array of objects inside the Column. Below is the code for my interface: export class User { result: boolean; messages: string; Column=[]; data=[]; } export class Column { name ...

The time-out counter fails to detect the input field

After writing a method to reset the timeout on mouse click, keyup, and keypress events, I realized that it does not account for input fields. This means that when I am actively typing in a field, the timeout will still occur. Below is the code snippet: ...

Adding Components Dynamically to Angular Parent Dashboard: A Step-by-Step Guide

I have a dynamic dashboard of cards that I created using the ng generate @angular/material:material-dashboard command. The cards in the dashboard are structured like this: <div class="grid-container"> <h1 class="mat-h1">Dashboard</h1> ...

Unable to interpret AJAX request using PHP

I am trying to implement a feature where file contents can be deleted upon the click of a button. I have set up an ajax request that sends two variables - the filename and the name of the person who initiated the deletion process. The PHP function is runni ...

Image-switching button

I'm new to JavaScript and struggling with my first code. I've been staring at it for two days now, but can't figure out what's wrong. The goal is to create an HTML page where the user can change an image by clicking on a button, and th ...

Protractor: How to Handle Multiple Browser Instances in a Non-Angular Application and Troubleshoot Issues with ignoreSynchronization

I have encountered an issue while using protractor to test a Non-Angular application. After implementing the browser.forkNewDriverInstance(), it appears that this function is no longer functioning correctly as I am receiving the following error message dur ...

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

How come CSS styles are not being applied to forms in AngularJS?

When attempting to apply CSS styles to a form in order to indicate invalid input, I encountered an issue. Even after using the important tag, the styles did not change. I created a dynamic form from JSON and now need to validate it. Following a suggestion ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

Top strategy for monitoring a user's advancement in reading different text segments

If you are familiar with zyBooks, I am looking to implement a similar feature where users can track the sections they have read and mark them as completed with a button. However, I am struggling conceptually with determining how best to structure my mongo ...