6,539 Points

Why not just use the string to pass the phone number as a property?

Hello. I did not see this question being asked yet. Why do we need to pass the phone number with the setter method and not just keep it as a property of the Owner class? Is there a special meaning to the phone number not having any other charters (normalizing the phone number)? Or is it just an example on how to use the setter method and what it can do? I completely understand that these are very powerful methods and I am sure that this is just a tip of an iceberg, but just trying to understand the concept with the phone number.

Thank you in advance.

1 Answer

Peter Vann
Peter Vann
Treehouse Moderator 31,438 Points


I don't know if this answers your question adequately (since I'm not sure the exact course/video/challenge), but I'll give my $0.02, as they say.

Setters and getters are cool because they can allow you to do more with a property than just store a variable.

They can allow you to do transformations, such a concatenation or changing to uppercase or lowercase or use math functions on the incoming/outgoing data.

You can also do validation, to make sure the data is appropriate and in the right format, etc., such as turning numbers into strings and vice-versa.

And in the case of phone numbers, you can use something like RegEx to make sure it's a valid phone number and not, say, an email address.

Something like this:

function phonenumber(inputtxt) {
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno)) {
    return true;
  else {
    alert("Not a valid phone number");
    return false;

(Of course, that's just a function, but you could use similar code in your setter/getter.)

Does that make sense?

More info:

I hope that helps.

Stay safe and happy coding!

6,539 Points

Thank you so much for your response! Sorry, I did not realize that I created a new question rather than ask under the proper video. The problem I was referring to is introduced in this video of the OOJS course . After rewatching the video, as well as doing some additional research, I understand that is more like "best practices" for storing phone number data.