Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

75
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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));

about 4 years ago · Juan Pablo Isaza Relatório

0

What's happening here is that you are multiplying a number and doing so until it reaches the desire result. But since it's not adding 1 with each step it can exceed the result. What you need is have separate variable to store the previous value:

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

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

Or having 1 less step is to do the calculation inside the while condition:

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

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda