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