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 Object-Oriented JavaScript Getters and Setters Object Interaction

Amanda Richardson
seal-mask
.a{fill-rule:evenodd;}techdegree
Amanda Richardson
Web Development Techdegree Student 13,776 Points

defining this._phone in the setter method

Ashley set the value of this._phone as

 set phone(phone) {
    const phoneNormalized = phone.replace(/[^0-9]/g, "");
    this._phone = phoneNormalized;
  }

But why didn't she just code it like this -

 set phone(phone) {
       this._phone = phone.replace(/[^0-9]/g, "");
  }

I tried it this last way and it seemed to work fine and just wondering why she took the extra step here.

1 Answer

Raphael Zamora
Raphael Zamora
7,470 Points

Hi Amanda Richardson,

Both statements accomplish the same thing.

I believe Ashley took the extra step declaring the phoneNormalized variable to better emphasize the steps we are taking before setting the property.

Similar to how we can be more explicit in declaring functions

function add(num1, num2) {
   const sum = num1 + num2;
   return sum;
}

Alternatively, we can be more concise and return the value directly without assigning extra variables

function add(num1, num2) {
   return num1 + num2;
}