My code just comes out with “odd”. What am I doing wrong?
Instructions:
Write a function named evenOdd that takes two numbers and returns an object with the numbers and whether they are even or odd.
Example:
If you pass 1,4 it should return {"1": "odd", "2": "even", "3": "odd", "4": "even"}
My code:
function evenOdd(num, num2) {
let obj = {};
for (let i = num; i <= num2; i++) {
if(obj[i] % 2 !== 0) {
obj[i] = "odd"
} else if(obj[i] % 2 !== 1){
obj[i] = "even"
}
}
return obj;
};
Your logic:
if(obj[i] % 2 !== 0) {
Why are you checking if obj[i]
is even? Shouldn’t you be checking if i
is even?
And your line } else if(obj[i] % 2 !== 1){
- the if
is redundant. There are only two possibilities, you’ve already checked if it’s odd so you don’t need to check if it’s even - a simple if
will do it.
1 Like
Thanks, for some odd reason I think after an if statement HAS to come an else.
Somehow, it’s still not passing:
function evenOdd(num, num2) {
let obj = {};
for (let i = num; i <= num2; i++) {
if(i % 2 !== 0) {
obj[i] = "odd"
}
if(i % 2 !== 1){
obj[i] = "even"
}
}
return obj;
};
I need to have zero pass as an empty object, but am I not already doing that?
EDIT: Nevermind, my people. Thanks to all of you guys, I’m finally understanding all of this better:
function evenOdd(num, num2) {
let obj = {};
for (let i = num; i <= num2; i++) {
if (num === 0 && num2 === 0){
obj = {};
} else if(i % 2 !== 0) {
obj[i] = "odd"
} else{
obj[i] = "even"
}
}
return obj;
};