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

209
Visualizações
Why does function only return on statement and not the others

So my function below is

const message = function (number) {
  for (let i = 0; i < 200; i++) {
    if (i % 7 == 0 && i % 9 == 0) {
      return "Why is the ground shaking";
    } else if (i % 7 == 0) {
      return "Here is the magic 7";
    } else if (i % 9 == 0) {
      return "Here is the magic 9";
    } else {
      return "You have failed";
    }
  }
};

console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));

But it always returns "Why is the ground shaking" not sure why though

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You should put i = number instead of i = 0

const message = function (number) {
  for (let i = number; i < 200; i++) {
    if (i % 7 == 0 && i % 9 == 0) {
      return "Why is the ground shaking";
    } else if (i % 7 == 0) {
      return "Here is the magic 7";
    } else if (i % 9 == 0) {
      return "Here is the magic 9";
    } else {
      return "You have failed";
    }
  }
};

console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));

Update: Removing the for loop

As mention in the comment section, the for loop is redundant here.

Your message(number) function has 1 argument, which is number, and if you have your if - else with return statements, your loop will execute only once on each function call (when the return occurs). You could put i < 1 or i < 2000, the result would be the same.

So what you can do is, remove the loop, and simply put your argument (number) instead of i in each of your if statements.

I'm not the best at explaining, but hope this helped.

const message = function (number) {
    if (number % 7 == 0 && number % 9 == 0) {
      return "Why is the ground shaking";
    } else if (number % 7 == 0) {
      return "Here is the magic 7";
    } else if (number % 9 == 0) {
      return "Here is the magic 9";
    } else {
      return "You have failed";
    }
};

console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));


about 4 years ago · Santiago Trujillo 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