Why do we need to use underscores for our object properties?

Question

Why do we need to use underscores for our object properties?

Answer

Adding underscores allows us to keep those properties hidden away from access, forcing the getters and setters to be used. For example, let’s say we wanted to make sure our dog’s name is always in ALLCAPS, we could do the following:

			let dog = {
		
_name: ‘Max’,
_breed: ‘Chihuahua’,
		
		
get name() {
				return this._name;
				},

				set name(nameIn) {
					this._name = nameIn.toUpperCase();
}
	};


console.log(dog); // output: { _name: 'Max', _breed: 'Chihuahua', name: [Getter/Setter] }
	

You can see when we console.log(dog) that using ._name and .name will return different things. So, we can update our dog’s name like this:

dog.name = ‘Sam’;

console.log(dog.name); // output: ‘SAM’