Menu Home

Getter and Setter

Hi everyone, and welcome to another exciting edition of Boring JavaScript! Today, we’re going to take a look at Getters and Setters in JavaScript. With any object, you normally have properties that you can read and write to simply by accessing them or making an assignment. Getters and Setters, though, let you create functions to be executed whenever you access the property or assign a value to it – giving you a lot of power in how your variables are processed.

Don’t like to read? The watch our video.

Get Back to Where You Once Belonged!

For our examples below, we’re going to use classes – but know that you can use them also on everyday objects.

A ‘Getter’ defines a function that is called whenever the calling application retrieves the contents of a variable. Normally, you would define a property like this:

class Animal {
	name = '';
    tempF = 0;
}

const myCat = new Animal();
myCat.name = "Fluffy";
myCat.tempF = 101.7;
console.log(`Cat ${myCat.name}'s temperature: ${myCat.tempF} F.`);

/* output
Cat Fluffy's temperature: 101.7 F.
*/

“animalName” (Line 2) is a property on the class “Animal”. It can be written to (Line 6) and read from (Line 8). You already know that.

A ‘Getter’ function, when defined, will execute a function whenever a calling application retrieves the value of a variable (Line 8 above). Which means that we are not limited to only returning any value set by the application – we can return anything.

Let’s change the code slightly to also calculate Celcius:

class Animal {
	animalName = '';
    tempF = 0;

    get tempC () {
        return (this.tempF - 32) * 5 / 9;
    }
}

const myCat = new Animal();
myCat.animalName = "Fluffy";
myCat.tempF = 101.7;
console.log(`Cat ${myCat.animalName}'s temperature: ${myCat.tempF} F (${myCat.tempC} C).`);

/* output
Cat Fluffy's temperature: 101.7 F (38.72222222222222 C)
*/

Notice Lines 5 through 7 and Line 13. Using the keyword ‘get’ defines a ‘Getter’ function. What this does is take the name of the function – in our case ‘tempC’ – and let JavaScript know that it is to be treated as a property on that class (or object). Therefore, we access it like we do on Line 13 – as if it was another property on the class.

Which means that everytime we change ‘tempF’ (as in Line 12), ‘tempC’ will get recalculated each time we access.

And here’s the real power: What this also means that is that ‘tempC’ is read-only. You will not be able to change the value of the variable! Try this:

myCat.tempF = 101.7;
console.log(`Cat ${myCat.name}'s temperature: ${myCat.tempF} F (${myCat.tempC} C)`);

myCat.tempC = 40;
console.log(`Cat ${myCat.name}'s temperature: ${myCat.tempF} F (${myCat.tempC} C)`);

/* output
Cat Fluffy's temperature: 101.7 F (38.72222222222222 C)
Cat Fluffy's temperature: 101.7 F (38.72222222222222 C)
*/

As you can see, any changes to ‘tempC’ are ignored.

Ok – now we’ve shown you how to ‘get’ a property and basically make it read-only. Can we do the same thing with writing a property? Certainly!

Setting Aside the Argument

You can also define a function to be called when ever an application changes the value of a property. That is called a ‘Setter’ function, and it is done with the ‘set’ keyword. Let’s take a look:

class Animal {

	name = '';
	#statistics = {
		tempF: 0,
		height: 0,
		weight: 0,
		tempC: 0
	}

	set tempF (tempF) {
		this.#statistics.tempF = tempF;
		this.#statistics.tempC = (tempF - 32) * 5 / 9;
	}

	set height (height) {
		this.#statistics.height = height;
	}

	set weight (weight) {
		this.#statistics.weight = weight;
	}

	get stats () {
		return this.#statistics;
	}

}

const myCat = new Animal();
myCat.name = "Fluffy";
myCat.tempF = 101.7;
myCat.height = 9.1;
myCat.weight = 7.9;

const stats = myCat.stats;

console.log(`
${myCat.name}'s Stats:
    TempF:  ${stats.tempF}
    TempC:  ${stats.tempC}
    Height: ${stats.height}
    Weight: ${stats.weight}
`)

/* output
Fluffy's Stats:
    TempF:  101.7
    TempC:  38.72222222222222
    Height: 9.1
    Weight: 7.9
*/

The ‘set’ keyword (Lines 11, 16, and 20) defines a function for what to do if an application assigns a value to anyone of the properties defined. Lines 32 through 34 set the variables ‘tempF’, ‘height’, and ‘weight’, and the functions store these in a private variable inside the class (with ‘tempF’ also settinging the ‘tempC’ variable, as in our first example).

The results of this is that you have defined three variables that are ‘write-only’. You can set the variables, but cannot retrieve them later. This basically ‘hides’ the variables from the consuming application. This is why we’ve setup a ‘Getter’ for the statistics variable so that the properties can be retrieved.

What happens if you try to read a variable that doesn’t have a ‘getter’ function? Let’ take a look:

const stats = myCat.stats;

console.log(`
${myCat.name}'s Stats:
    TempF:  ${stats.tempF}
    TempC:  ${stats.tempC}
    Height: ${stats.height}
    Weight: ${stats.weight}
`)

console.log(myCat.weight);

/* output
Fluffy's Stats:
    TempF:  101.7
    TempC:  38.72222222222222
    Height: 9.1
    Weight: 7.9

undefined
*/

It comes back as ‘undefined’ – which, of course, it is.

The Video

We have a video available that shows examples of getters and setters.

Shameless Plugs

You can find us everywhere!

Check out all our videos at: https://www.boringjavascript.com

Github Repository: https://github.com/TheVirtuoid/boringjavascript

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: