JavaScript Function Failing to Produce Output

I have created a function that reduces two numbers using the relationship of fractions. The function is working perfectly, but there is an issue with it not returning the value as expected. I have tried different approaches such as declaring a new variable and then returning it, but still no luck. I even added console.logs to check if the function was stopping at a certain point, but unfortunately, it does not return anything.

Here is my code:

function reduceFraction(n, d) {
    var numerator = n;
    var denominator = d;

    if (n % 7 === 0 && d % 7 === 0) {
        numerator /= 7;
        denominator /= 7;
        console.log('Divided by 7');
        reduceFraction(numerator, denominator);
    } else {
        if (n % 5 === 0 && d % 5 === 0) {
            numerator /= 5;
            denominator /= 5;
            console.log('Divided by 5');
            reduceFraction(numerator, denominator);
        } else {
            if (n % 3 === 0 && d % 3 === 0) {
                numerator /= 3;
                denominator /= 3;
                console.log('Divided by 3');
                reduceFraction(numerator, denominator);
            } else {
                if (n % 2 === 0 && d % 2 === 0) {
                    numerator /= 2;
                    denominator /= 2;
                    console.log('Divided by 2');
                    reduceFraction(numerator, denominator);
                } else {
                    console.log('Was not divided by anything');
                    var reduced = numerator + "/" + denominator;
                    return reduced; //console.log(numerator + "/" + denominator); logs 1/18
                }
            }
        }
    }
}
reduceFraction(3, 54);

I am not sure if having nested if statements is causing any issues, but currently, this is the only way I can think of to reduce a fraction. Thank you in advance for your help.

Answer №1

To properly utilize a recursive function, it is important to include the return statement:

Substitute every instance of

    reduceFraction(numerator, denominator);

with :

    return reduceFraction(numerator, denominator);

Answer №2

you must give back it

 function simplifyFraction(numerator, denominator) {
    var num = numerator;
    var denom = denominator;

    if (num % 7 === 0 && denom % 7 === 0) {
        num /= 7;
        denom /= 7;
        console.log('Divided by 7');
        return simplifyFraction(num, denom);
    } else {
        if (num % 5 === 0 && denom % 5 === 0) {
            num /= 5;
            denom /= 5;
            console.log('Divided by 5');
            return simplifyFraction(num, denom);
        } else {
            if (num % 3 === 0 && denom % 3 === 0) {
                num /= 3;
                denom /= 3;
                console.log('Divided by 3');
                return simplifyFraction(num, denom);
            } else {
                if (num % 2 === 0 && denom % 2 === 0) {
                    num /= 2;
                    denom /= 2;
                    console.log('Divided by 2');
                    return simplifyFraction(num, denom);
                } else {
                    console.log('Was not divided by anything');
                    var result = num + "/" + denom;
                    return result; //console.log(num + "/" + denom); logs 1/18
                }
            }
        }
    }
}
return simplifyFraction(3, 54);

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

Generate a hyperlink within a paragraph

Can anyone provide tips on how to turn a string from Json into a paragraph with a hyperlink included? <p>Dumy Dumy Dumy Dumy Dumy Dumy Dumy DumyDumyDumyDumy abc.com </p> Currently, the paragraph displays as is, but I would like to make abc.c ...

Firefox MediaSourceExtension now has enhanced mp3 support

Currently exploring the integration of adaptive and progressive audio streaming in the browser without the need for plugins. MSE is the HTML5 API that I've been anticipating, now available in FF 42. However, I'm encountering issues with audio fo ...

How can I locate the element immediately preceding $(this)?

Struggling to retrieve the value of the $(.subname) when the .bigadminbutton is clicked and calling the updateSub() function. I have tried various methods like prev, sibling, parent, children, find, but none seem to work. This minor task is taking up too ...

Inquiries for Web-Based Applications

As I contemplate coding my very first webapp, I must admit that my skills are somewhere between beginner and intermediate in html, css, js, jquery, node, sql, and mongodb. However, the challenge lies in not knowing how to bring my vision to life. My ulti ...

Mockgoose encountered an error during shutdown: ENOTCONN

It's making me lose my mind. I'm currently executing some unit tests with the following configuration import mongoose from "mongoose"; import mockgoose from "mockgoose"; import chai from "chai"; import chaiAsPromised from "chai-as-promised"; i ...

Obtaining a timestamp from a date string with a specific timezone/locale is simple and

I need to extract timestamps from JSON items with a date field formatted like this: 'Wed, 14 May 2014 20:19:00 BST' Is there a way to retrieve the timestamp from this specific string format? Attempting to create a Date object doesn't seem ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

"Using ng-click to access values from other elements in AngularJS

Can someone help me retrieve the value of an input field when a button is clicked? Here is my controller code: app.controller('MainCtrl', function($scope) { $scope.test = function(val) { alert(val); } }); This is my HTML snippet: < ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Bootstrap modal not displaying in full view

I recently ran into some issues while using a jQuery plugin with my bootstrap modal on my website. After implementing jQuery.noConflict(), I encountered a problem where the program no longer recognized $, forcing me to replace all instances of it with jQue ...

What is the best way to locate this particular element on the webpage?

After using the right-click and selecting inspect element, I located the code of the desired element on the webpage: <input type="text" ng-if="!editing" ng-model="item.Price" ng-click="inputFocus()" ts="" required="" placeholder="قیمت :" class="ng- ...

Extracting information from HTML and transferring it to Javascript using jQuery

My goal is to utilize jsGrid for showcasing database data without repeating code extensively. I aim to generate separate grids for each <div> with a specific id while passing on relevant values accordingly. To clarify my objective, here's a sni ...

When transmitting a variable from JavaScript to PHP using Ajax, the data appears to be missing

While attempting to pass a simple string variable using an onclick event, I encountered an issue where the request was successful but the response in the console displayed as empty. Additionally, the xvar variable did not come through properly resulting in ...

"Learn how to retrieve and assign a value to a select2 dropdown in Vue.js

Currently, I am utilizing vuejs to create and delete dynamic select elements, which is functioning properly. To view the working example, please click here: https://jsfiddle.net/nikleshraut/fgpdp700/2/ var vm = new Vue({ el: "#app", data: { opt ...

Using Formik inside Material-UI's table components

My goal is to design a material UI table where each cell acts as a Formik input. However, I've encountered errors with Material UI when attempting to use a Formik Object within TableBody or TableItem tags. Here's an example image of what I' ...

Creating a proxy for an HTTP video stream (from VLC) using NodeJS and ExpressJS

Using VLC 2.2.1, I am able to create an HTTP stream of my webcam from a computer named server. If I open VLC on another computer, client, and enter the network stream http://server:8080, the webcam video displays perfectly. A Wireshark capture of the HTT ...

Ensure that the JSON file contains values within an array of objects

Currently, I am working with JavaScript and have a JSON file containing Twitter data. Accessing the data is not an issue as I can easily retrieve it using something like: var content = data.text;, allowing me to modify a div using innerHTML. However, I am ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Improve the performance of your three.js project by utilizing JavaScript arrays instead of importing OBJ or GLTF files

I've noticed that loading OBJ/GLTF/GLB models into my three.js application can be time-consuming. On the other hand, declaring JavaScript arrays of vertices and indices with the same data and creating a new object is much quicker (and reduces file siz ...

How can you toggle the visibility of a text based on the selection of a jQuery radio button?

Is it possible to dynamically enable or disable a field based on the selection of a radio button? Here are the rules: The field should only be active when the "Inactive" radio button is selected Check out the code snippet below for reference: Radio B ...