Daniel Kent
Daniel Kent

Reputation: 63

How is my variable changing value during the return statement in a recursive algorithm?

I am doing an exercise with linked lists in Javascript. As part of my solution, I have a function that takes a linked list of one digit integers and converts it to a single number. The value being returned is not the same as the value logged to the console the line before the return.

for example, if I input (2 -> 4 -> 3), my console.log is 342, just as it should, but the value returned in otherFunction is 386. Input (5 -> 6 -> 4) logs 465, but returns 535.

How is the value of num changing?

function parseListNumber(list, num = 0, multiplier = 1) {
    digitValue = list.val * multiplier;
    multiplier *= 10;
    num += digitValue;
    if (list.next) {
        return num + parseListNumber(list.next, num, multiplier);
    } else {
        console.log(num) // num is correct here
        return num;
    }
}

function otherFunction(list) {
    parseListNumber(list); // returned value is now somehow larger
};

Upvotes: 0

Views: 30

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50759

You're adding num to your recursive call each time you enter your if statement. If you remove this, then when you hit your base case, your value will be carried back up through the previous recursive calls and remain unchanged.

See example below:

const list = {
  val: 2,
  next: {
    val: 4,
    next: {
      val: 3
    }
  }
};

function parseListNumber(list, num = 0, multiplier = 1) {
  let digitValue = list.val * multiplier;
  multiplier *= 10;
  num += digitValue;
  if (list.next) {
    return parseListNumber(list.next, num, multiplier); // remove `num +` (use tail recursion)
  } else {
    console.log(num) // num is correct here
    return num;
  }
}

function otherFunction(list) {
  console.log("Actual res: ", parseListNumber(list));
};

otherFunction(list);

Upvotes: 3

Related Questions