Chapter 17 Getters and Setters - Logging Activity & Property Value Validation

Hello Kirupa,
How are you doing?

I didn’t get it the explanation of the following code. Please, can you shed some more light into this.

Logging Activity:
‘use strict’;

var superSecureTerminal = {
allUserNames: [],
_username: “”,

showHistory() {
console.log(this.allUserNames);
},
get username() {
return this._username;
},
set username(name) {
this._username = name;
this.allUserNames.push(name);
}
}

var myTerminal = Object.create(superSecureTerminal);
myTerminal.username = “Michael Gary Scott”;
myTerminal.username = “Dwight K. Schrute”;
myTerminal.username = “Creed Bratton”;
myTerminal.username = “Pam Beasley”;
myTerminal.showHistory();

Property Value Validation:
let person = {
_name: " ",
_age: " ",
get name() {
return this._name;
},
set name(value) {
if (value.length > 2) {
this._name = value;
} else {
console.log(“Name is too short!”);
}
},
get age() {
return this._age;
},
set age(value) {
if (value < 5) {
console.log(“Too young!”);
} else {
this._age = value;
}
},
get details() {
return "Name: " + this.name + ", Age: " + this.age;
}
}

Please can you explain the above codes in detail with their output and how to console.log these two codes and why we use it in what scenarios we can use these types of functionalities.

I apologize, I am troubling you like this. I am new to coding, and I am not from a tech background. Also, if you could recommend any resources like your book for beginners like me.

Thank you so much!!

Hi @Anand_Singh1 - one of the main reasons to use getters and setters is to provide a bit of flexibility on your end on what happens when someone sets a value or retrieves a value.

The alternative is to just expose variables directly that anybody can read and write. If we do that, what you lose is the ability to do any sort of processing of the data before it gets out. Logging is an example highlighted here. Same with adding people to the allUserNames array.

To the end-developer, this code looks like a variable setting:

myTerminal.username = “Dwight K. Schrute”;

Behind the scenes, we know there is a lot more happening thanks to using setter/getter.

Hope this helps. Let me know if I can clarify more :slight_smile:

Cheers,
Kirupa