Getter Property

Getter property is used when we want to modify the property before using it to the template. There is another use case when we do not want to create a variable in the component.

The getter function always executes after the constructor and connectedCallback in the lifecycle Hooks.


get anyName() { … }

Let’s Play with the example

   <lightning-input type="number" name="input1" onchange={handleChange} label="Enter number" ></lightning-input>
   <lightning-input type="number" name="input2" onchange={handleChange} label="Enter number" ></lightning-input>
   <b>The sum {sumtwonumber}</b>

getter property

In the above html we have two input fields will accept the number and the getter property will calculate the sum.

import { LightningElement, track } from 'lwc';

export default class salesforcedriller extends LightningElement {
   @track firstNumber;
   @track secondNumber;

           this.firstNumber =;
       }else if('input2'){
           this.secondNumber =;

   get sumtwonumber(){
       //parseInt Converts a string to an integer.
       if(this.firstNumber && this.secondNumber){
           return parseInt(this.firstNumber)+parseInt(this.secondNumber);

calculate sum

Explanation: As you can see on the top there is a method called sumtwonumber with get property. Getter function with name sumtwonumber calculate the sum of those two properties dynamically. we have validated the input before processing it for sum.
Handlechange event will call when the input key is pressed by the will update the variables.



Subscribe Now