Search code examples
javascriptloopswhile-loopreturnbreak

Why is the return keyword not giving me the desired result?


There is this challenge that I'd love to overcome. I've been stuck for almost 2 weeks. Here is the code:

function multiply(top,bottom){
  var num = top;
  var multiple = 2;
  while (num <= bottom){
    num *= multiple;
    console.log(num);
  }
  return num;
}

console.log(multiply(5, 100));// expected outcome is 80 

I'd love to return the last result from the console.log which is 80 but each time I use the return keyword, it doesn't bring the desired result.


Solution

  • You have another variable which keeps track of the next multiple, so that we can check it before we assign it to num.

    function multiply(top,bottom) {
     var num = top;
     var multiple = 2;
     var next = num * multiple;
     while(next < bottom) {
      num = next;
      next = num * multiple;
     }
     return num;
    }
    
    console.log(multiply(5, 100));