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

119
Visualizações
Loop between 2 given numbers and check if they are even or odd JavaScript

I need to iterate between 2 numbers and for each number I need to specify if it's odd or even

I have accomplished iterating between 2 numbers, but I cannot work out how to add if they are even or odd. I've tried so many different options and I'm still stuck.

const goThroughNumbers = (start:number, end:number)=>{
    var num = []
        for(var i = start; i <= end; i++){
            num.push(i++) }  

    {
        if(i % 2 ===0 ){
            console.log(`${i} - Even`)
         } else{
            console.log(`${i} - Odd`)
         }
            
    }
    
}

console.log(goThroughNumbers(3, 7));

Expected output:

> 3 - odd
> 4 - even
> 5 - odd
> 6 - even
> 7 - odd
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There are some syntax errors in your code: remove the extraneous { ... } that wraps your if/else block. Also, you want to perform the console logging inside the for loop to achieve the output you intended. There is no need to store the numbers into a num array, since you don't need it.

const goThroughNumbers = (start, end) => {
  for (let i = start; i <= end; i++) {
    if (i % 2 === 0) {
      console.log(`${i} - Even`)
    } else {
      console.log(`${i} - Odd`)
    }
  }
}

goThroughNumbers(3, 7);

You can even further condense the logic down to using ternary operators in your console.log:

const goThroughNumbers = (start, end) => {
  for (let i = start; i <= end; i++) {
    console.log(`${i} - ${i % 2 ? 'Even' : 'Odd'}`);
  }
}

goThroughNumbers(3, 7);

about 4 years ago · Juan Pablo Isaza Relatório

0

I would extract the evenOdd logic, and return a value:

const evenOdd = (n) => n % 2 ? 'odd' : 'even'

function goThroughNumbers(start, end) {
  let ret = []
  for (let i = start; i <= end; i++) {
    ret = [...ret, evenOdd(i)]
  }
  return ret
}

const result = goThroughNumbers(3, 7)
console.log(result)

I think breaking up functions into smaller parts is more flexible, than directly logging the values out.

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