Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

olhahelena
olhahelena
6,731 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

Hi!

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:

https://teamtreehouse.com/library/practice-getters-and-setters-in-javascript

I hope that helps.

Stay safe and happy coding!

olhahelena
olhahelena
6,731 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 https://teamtreehouse.com/library/object-interaction . After rewatching the video, as well as doing some additional research, I understand that is more like "best practices" for storing phone number data.