Object for odd and even #'s

Object for odd and even #'s
0

#1

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;
};

#2

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.


#3

Thanks, for some odd reason I think after an if statement HAS to come an else.


#4

Based on the problem description, the object returned for call of evenOdd(1, 4) would only have two properties (“1” and “4”). It is not until you look at the expected object they want you to return, that you realize they want an object with property names which are between the first and second number (inclusive) having the applicable values “even” or “odd”.


#5

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;
};

#6

The instructions do not say, but if you assume the first argument’s value is always less than or equal to the second argument’s value and the first argument’s value is not negative, then the following code will work:

const evenOdd = (min, max) => {
  let obj = {};
  min = min || 1;
  for (let i = min; i <= max; i++) {
    obj[i] = !(i % 2) ? 'even' : 'odd';
  }
  return obj;
};

If you have to account for negative numbers, then:

const evenOdd = (min, max) => {
  let obj = {};
  for (let i = min; i <= max; i++) {
    if (i % 2 !== 0) {
      obj[i] = 'odd';
    } else if (i !== 0) {
      obj[i] = 'even';
    }
  }
  return obj;
};