Created a factory function, but my conditionals are not working and it accepts anything

Hi all,

I just finished the topic on getters and setters and factory functions and tried to recreate my own. However I am not able to get my conditional to work in the setter method:

var facebookAccount = (name, age, location, hobbies) => {
  return {
    name,
    age,
    location,
    hobbies,
    set ages(num) {
      if (typeof num === 'number') {
        this.age = num;
      } else {
        return 'Please enter a valid number';
      }
    }
  }
};

var Tony = facebookAccount('Anthony', 20, 'New York', 'Video games');
Tony.age = 'high'
Tony.age; // comes up as 'high'

My ‘else’ conditional for ‘age’ did not come up and I was able to change the ‘age’ property to a string even though it should only accept numbers. Any idea what I did wrong? Thanks

Hello, and welcome to the forums.

You named your setter ages, so you’d need to use Tony.ages = 'high' to test it. Using Tony.age directly bypasses your code in the setter. You can add some console.log() statements in your setter to see what I mean.

Thank you very much! I also realised it doesn’t work if I use the ‘return’ statement and only shows the ‘Please enter a valid number’ if I use console.log, unless I am missing something…

Regardless thanks very much :slight_smile: