Create Getter / Setter in Javascript

Create Getter / Setter in Javascript

ยท

2 min read

What is getter and setter?

Well, if you're coming from OOP backgrounds like Java or C# you might familiar with the concept of getter and setter but in javascript how getter setter works? or if you are new to javascript then you should know how it works.

Let's start with the basic object ๐Ÿ–‹

const person={
  firstName:'Rajesh'
  lastName:'Prajapati'
}

The above object has first name and last name and somewhere in our application if need to showcase the full name then we have to do something like this:

console.log('Fullname: ' + person.firstName + ' ' + person.lastName);
 // or
console.log(`Fullname: ${person.firstName}  ${person.lastName} `);

This kind of problem of getting values is evaluated can be eliminated by using a getter to personalized with function. let's modify the person object and new function fullName-

const person={
  firstName:'Rajesh',
  lastName:'Prajapati',
  fullName() {
    return `Fullname: ${person.firstName}  ${person.lastName} `;
  }
}

// call fullname
console.log(person.fullName());

I've created a full name function and just simply return the above console statement. and it works perfect but its values are read-only also not able to set values like person.firstName = 'Rama';.

Now we should get fullname as property like console.log(person.fullName); but make it work we have to make changes in bellow object- using getter and setter.

// getter => access properties
// setter => modify the property
const person={
  firstName:'Rajesh',
  lastName:'Prajapati',
  get fullName() {
    return `Fullname: ${person.firstName}  ${person.lastName} `;
  }
}
// call fullname as prop
console.log(person.fullName);

Similarly, we can create setter to set the values

const person={
  firstName:'Rajesh',
  lastName:'Prajapati',
  get fullName() {
    return `Fullname: ${person.firstName}  ${person.lastName} `;
  },
  set fullName(values) {
  const data = values.split(' '); // it will return array
  this.firstName = data[0];
  this.lastName = data[1]; 
  },
}
// to set the value
person.fullName = 'Manish Prajapati';
console.log(person);

Now you can easily start writing setter and getter in your javascript program. if you find helpful this post do like and share with others that might help someone ๐Ÿ‘

Thanks for reading ๐Ÿ™