Guide: How to use Getters and Setters in JavaScript: Complete Guide

Getters and setters are functions or methods used to create get and set the values ​​of variablesThe getter-setter concept is common in computer programming: almost all high-level programming languages ​​come with a set of syntax to implement getters and setters, including JavaScipt. In this post, we’ll see what getters-setters are, and how to create and use them in JavaScript

Getters-setters and encapsulation

The idea of ​​getters and setters is always mentioned in combination with encapsulationEncapsulation can be understood in two ways First, it is the setting up of the data-getters-setters trio to access and change that data. This definition is useful when certain operations, such as validation, need to be performed performed on the data before saving or viewing – getters and setters provide the perfect home before. Second, there is a stricter definition according to which encapsulation is done hide data, to make it inaccessible from other code, except by the getters and settersWe don’t end this way up accidentally overwriting important data with a different code in the program.

Create getters and setters

Because getters and setters are actually functions that get / change a value are there more than one way to create and use them. The first way is: var obj = {foo: ‘this is the value of foo’, getFoo: function () {return this.foo;}, setFoo: function (val) {this.foo = val;}} console.log (obj.getFoo ()); // “this is the value of foo” obj.setFoo (‘hello’); console.log (obj.getFoo ()); // “Hey” This is the easiest way to create getters and setters. There is a property foo and there are two methods: getFoo and setFoo to back and assign a value to that property. A more “official” and robust way to create getters and setters is through the retrieve and set keywords To create a getter, place the get keyword for a function declaration that will serve as the getter method, and use the set keyword in the same way create a setterThe syntax is as follows: var obj = {fooVal: ‘this is the value of foo’, get foo () {return this.fooVal;}, set foo (val) {this.fooVal = val;}} console.log (obj.foo); // “this is the value of foo” obj.foo = ‘hello’; console.log (obj.foo); // “Hey” Note that the data can only be saved under a property name (fooVal) that is different of the name of the getter-setter methods (foo) because a property is the getter-setter cannot contain the data also. If you choose to create keyword getters and setters, you can use the assignment operator to set the data and the dot operator to get the data, the same way you would open / set the value of a regular property. However, if you choose the first way to encode getters and setters, you must call the setter and getter methods using the function call syntax because they are typical functions (nothing special like the ones created with the keywords get and set). There is also a chance that you will end up up accidentally assign a different value to the properties that those getter-setter methods contain and lose them completelySomething you don’t have to worry about with the later method. So you can see why I said it second technique is more robust If for some reason you prefer the former technique, create the properties with the getter-setter methods read only by making them using Object.definePropertiesProperties created via Object.defineProperties Object.defineProperty and Reflect.defineProperty automatically configure to writable: false which means read only / * Overwrite Prevention * / var obj = {foo: ‘this is the value of foo’}; Object.defineProperties (obj, {‘getFoo’: {value: function () {return this.foo;}}, ‘setFoo’: {value: function (val) {this.foo = val;}}}); obj.getFoo = 66; // getFoo will not be overwritten! console.log (obj.getFoo ()); // “this is the value of foo”

Operations within getters and setters

Once you’ve introduced the getters and setters, you can go ahead and perform operations on the data before changing or returning it. In the code below, in the getter function is the data concatenated with a string before it is returned, and in the setter function a validation of whether the value is a number or not is performed before n is updated. var obj = {n: 67, get id () {return ‘The ID is:’ + this.n;}, set id (val) {if (typeof val === ‘number’) this.n = val; }} console.log (obj.id); // “The ID is: 67” obj.id = 893; console.log (obj.id); // “The ID is: 893” obj.id = ‘hello’; console.log (obj.id); // “The ID is: 893”

Protect data with getters and setters

So far we have covered the use of getters and setters in the first context of encapsulation. Let’s go to the second, ie how to hide data from external code with the help of getters and setters. The institution up getters and setters does not mean that the data can only be accessed and modified through those methods. In the following example it is instantly changed without touching the getter and setter methods: var obj = {fooVal: ‘this is the value of foo’, get foo () {return this.fooVal;}, set foo (val) {this.fooVal = val;}} obj.fooVal = “hello”; console.log (obj.foo); // “Hey” We haven’t used the setter yet directly changed the data (fooVal)The data we initially set in obj is now gone! To prevent this (accidentally), you must need some protection for your data. You can add that by scope limitation from where your data is available. You can do that on both block scoping or function scoping One way is to use a block range within which the data is defined using the let keyword which limits the scope to that block. A block range can be created by inserting your code within a few bracesWhen creating a block scope, make sure that leave a comment above ask to leave the bracket alone so that no one removes the brackets accidentally think it has a few extra excess braces in the code or add a label to the block range. / * BLOCK SCOPE, leave the bracket alone! * / {let fooVal = “this is the value of foo”; var obj = {get foo () {return fooVal;}, set foo (val) {fooVal = val}}} fooVal = “hello”; // does not affect the fooVal in the block console.log (obj.foo); // “this is the value of foo” FooVal change / create outside the block does not affect the fooVal referenced within the getters setters. The most common way to protect the data with scoping is through keep the data within a function and return an object with the getters and setters of that function. function myobj () {var fooVal = “this is the value of foo”; return {get foo () {return fooVal;}, set foo (val) {fooVal = val}}} fooVal = “hello”; // does not affect our original fooVal var obj = myobj (); console.log (obj.foo); // “this is the value of foo” The object (with the foo () getter-setter in it) returned by the myobj () function is stored in obj, and then obj gets used call the getter and setter There is also another way to prevent your data from being overwritten without limiting its scopeThe logic behind it is as follows: how can you change a piece of data if you don’t know what it’s called? If the data is a not so easily reproducible variable / property name, chances are no one (even us) will end up override by assigning a value to that variable / property name. var obj = {s89274934764: ‘this is the value of foo’, get foo () {return this.s89274934764;}, set foo (val) {this.s89274934764 = val;}} console.log (obj.foo); // “this is the value of foo” See, that’s one way of working things out. While the name I chose isn’t exactly a good one, so can you use arbitrary values ​​or symbols to create property names as suggested by Derick Bailey in this blog post. Its main purpose is to keep the data hidden of other code and allow a getter-setter pair to access / update.

When should you use getters and setters?

Now comes the big question: start assigning your getters and setters on all your data now? If you hide data, then there is no other choice But if your data is seen by other code is fine, you should still use getters setters just to bundle it up with code who does some operations on it? I would say YesCode adds up Very fastCreate microunits of individual data with a custom getter-setter gives you a certain independence to work on said data without affecting other parts of the code.

How to use Getters and Setters in JavaScript: Complete Guide: benefits

Faq

Final note

I hope you like the guide How to use Getters and Setters in JavaScript: Complete Guide. In case if you have any query regards this article you may ask us. Also, please share your love by sharing this article with your friends. For our visitors: If you have any queries regards the How to use Getters and Setters in JavaScript: Complete Guide, then please ask us through the comment section below or directly contact us. Education: This guide or tutorial is just for educational purposes. Misinformation: If you want to correct any misinformation about the guide “How to use Getters and Setters in JavaScript: Complete Guide”, then kindly contact us. Want to add an alternate method: If anyone wants to add more methods to the guide How to use Getters and Setters in JavaScript: Complete Guide, then kindly contact us. Our Contact: Kindly use our contact page regards any help. You may also use our social and accounts by following us on Whatsapp, Facebook, and Twitter for your questions. We always love to help you. We answer your questions within 24-48 hours (Weekend off). Channel: If you want the latest software updates and discussion about any software in your pocket, then here is our Telegram channel.

How to use Getters and Setters in JavaScript  Complete Guide 2021  2022  - 15How to use Getters and Setters in JavaScript  Complete Guide 2021  2022  - 3How to use Getters and Setters in JavaScript  Complete Guide 2021  2022  - 60How to use Getters and Setters in JavaScript  Complete Guide 2021  2022  - 86