Barbara Jacob
Barbara Jacob

Reputation: 286

Scope weirdness when recursing

I am just playing aimlessly, and I stumbled across something I don't get.

var result;
// [.............. more stuff ..............]
function iterate(n) {
 if (isDivisor(n)) {
   if (checkIfPrime(n)) {
        result = n;
        return result;
   }
   iterate(n-2);
 }
 iterate(n-2);
}

result = iterate(startN)
console.warn("result is ", result)

//(isDivisor() and checkIfPrime() omitted because irrelevant to the problem

So, the code works fine, in the restrict sense that the recursion stops once the expected value is reached. But! in the console I get undefined. result is a global and is not redeclared inside any function, specifically not inside iterate(). n has the correct value when iterate() returns. iterate() has access to the global scope (and lives into it) So, how could it possibly result be undefined... ?

I am probably only having a selective blindness attack but I really don't see where the scope goes astray.

Upvotes: 0

Views: 55

Answers (2)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

Your function returns undefined, and you are assigning its result to the result variable.

You should return the result from the function:

function iterate(n) {
 if (isDivisor(n)) {
   if (checkIfPrime(n)) {
        return n;
   }
   return iterate(n-2);
 }
 return iterate(n-2);
}

var result = iterate(startN);
console.log(result);

Upvotes: 4

hugomg
hugomg

Reputation: 69954

If a Javascript fiunction exits without getting to a return statement, its return value will be undefined. This will happen to your function unless you have isDivisor(n) and checkIfPrime(n) both being true.

Perhaps you were intending to do

function iterate(n) {
 if (isDivisor(n)) {
   if (checkIfPrime(n)) {
        result = n;
        return result;
   }
   return iterate(n-2); // <----
 }
 return iterate(n-2); // <----
}

instead?

Upvotes: 3

Related Questions