Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object is not updating in recursively called function in JavaScript

Tags:

javascript

I am trying to get data through recursive function, but my response object is not updating when the recursive function is called;

    function checkData(id) {
    var response = {
        new_id: '',
        status: false
    }

    var order = somefunction(id);

    var isOriginal = order.isOriginal
    var enddate = order.enddate
    var new_id = order.originalId

    // first check
    if (enddate == '' && isOriginal) {
        response.new_id = new_id;
        response.status = true;
    }

    //second check
    if (!isOriginal) {
        if (new_id) {
            checkData(new_id); // recursive call
        }
    }
    return response;
}

if the second check condition meets, it loads the data but when the response is consoled it shows the initial data which initialized earlier. the response variable is not updating with a recursive call. However, it updates if the first check passed.

like image 605
Mangrio Avatar asked Oct 19 '25 10:10

Mangrio


1 Answers

Based on the comments @Fred Stark, successfully solved by retuning the recursive call,

function checkData(id) {
var response = {
    new_id: '',
    status: false
}

var order = somefunction(id);

var isOriginal = order.isOriginal
var enddate = order.enddate
var new_id = order.originalId

// first check
if (enddate == '' && isOriginal) {
    response.new_id = new_id;
    response.status = true;
}

//second check
if (!isOriginal) {
    if (new_id) {
        return checkData(new_id); // recursive call ---> called return here
    }
}
return response;
}
like image 140
Mangrio Avatar answered Oct 22 '25 00:10

Mangrio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!