Charles Moonen
Charles Moonen

Reputation: 5

Return and log of the same variable don't match

I have an array named bars that contains the active id numbers of progress bars. I want to go through this array to find the first value that does not match its index (for finding the lowest available ID). My (apparently incorrect) solution is as follows:

var bars = [0,1];
function getNewBarID(counter) {
  var i = counter || 0; //sets i to counter value if it exists, or to 0 if it doesn't
  if (bars[i] == i) {
    ++i;
    getNewBarID(i);
  } else {
    console.log(i);
    return i;
  }
}
getNewBarID();

When I run this (in a node console and in chrome js console) it logs 2 to the console and returns undefined, while it should return 2.

what!?

edit: when the function is run with an empty array, it both returns and logs 0 (more what!?)

Upvotes: 0

Views: 125

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138457

Probably:

return getNewBarID(i);

But to be honest it should rather be:

const newBar = bars.find((el,i) => el !== i) || bars.length; //newBar contains the result...

or a bit longer using a good old for loop:

function getNewBarID(){
  let i = 0;
  while(bars[i] === i) i++;
  return i;
}

Try it

Upvotes: 2

Koenigsberg
Koenigsberg

Reputation: 1799

That is because you first run

getNewBarID();

where

if (bars[i] == i) 

is true. From there you make the next call, yes, but the first call executes without a return value. You get a return value eventually, however first you executed twice without returning anything. Just add a return to the if-case:

return getNewBarID(i);

Upvotes: 0

Related Questions