Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!