Getter and Setter and Js Operators

 1) Getters and Setters


JavaScript Getter and Setter:


In JavaScript, there are two kinds of object properties:


1) Data properties

2) Accessor properties


Data Property:


const student = {

    // data property

    firstName: 'Monica';

};

Accessor Property:

In JavaScript, accessor properties are methods that get or set the value of an object. 

For that, we use these two keywords:


get - to define a getter method to get the property value

set - to define a setter method to set the property value


JavaScript Getter:

In JavaScript, getter methods are used to access the properties of an object. 

Note: To create a getter method, the get keyword is used.


JavaScript Setter:

In JavaScript, setter methods are used to change the values of an object.

Note: To create a setter method, the set keyword is used.

      Setter must have exactly one formal parameter.

let student = {
firstName: 'Swati',
get getName() {
return this.firstName;
},
set changeName(newName) {
this.firstName = newName;
}
};


console.log(student.firstName);//Swati
console.log(student.getName);//Swati
student.changeName = 'Roshni';
console.log(student.getName);//Roshni










JavaScript Object.defineProperty():

In JavaScript, you can also use the Object.defineProperty() method to add getters and setters.

let student = {
firstName: 'Swati'
};
Object.defineProperty(student, "getName", {
get: function () {
return this.firstName;
},
});
Object.defineProperty(student, "changeName", {
set: function (newName) {
this.firstName = newName;
},
});
console.log(student.firstName);
console.log(student.getName);
student.changeName = 'Roshni';
console.log(student.getName);











2) JS Operators:


JavaScript Operators:


What is an Operator?

In JavaScript, an operator is a special symbol used to perform operations on operands 

(values and variables). For example,


2 + 3; // 5

Here + is an operator that performs addition, and 2 and 3 are operands.


JavaScript Operator Types:


Assignment Operators: used to assign values to variables.

















Arithmetic Operators: used to perform arithmetic calculations.


















Comparison Operators: Comparison operators compare two values and return a boolean value, either true or false.


















Logical Operators: Logical operators perform logical operations and return a boolean value, either true or false.












Bitwise Operators: Bitwise operators perform operations on binary representations of numbers.


























String Operators: you can also use the + operator to concatenate (join) two or more strings.


Others:



Comments

Popular posts from this blog

Object.getOwnPropertyDescriptor & Object.defineProperty Methods.

Scope and Closures / Callback Hell

DOM - Document Object Model (document.getElementById etc.)