-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
In JavaScript, getters and setters are special methods that allow controlled access to object properties. They are part of JavaScript’s object-oriented features and help manage data encapsulation, validation, and dynamic computation of values.
Getter: A method that retrieves a property value when the property is accessed.
Setter: A method that updates a property value when a new value is assigned.
Using getters and setters ensures that data is accessed or modified safely, reducing potential bugs or invalid state changes. They are widely used in complex applications, API response handling, and modern frameworks.
A getter allows a property to be accessed like a normal property while actually calling a function behind the scenes.
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName); // John Doe
fullName
is accessed without parentheses.
Getters are useful when a value is derived from other properties, for example, combining firstName
and lastName
.
Getters can help compute values dynamically without storing extra data.
They improve readability by exposing a property-like interface for computed values.
A setter allows you to execute logic when a property value is updated.
const person = {
firstName: "John",
lastName: "Doe",
set fullName(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
person.fullName = "Alice Smith";
console.log(person.firstName); // Alice
console.log(person.lastName); // Smith
The setter receives a single argument representing the new value.
Inside the setter, you can split, validate, transform, or modify values before storing them.
Objects can have both a getter and a setter for the same property, allowing controlled read/write access.
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
console.log(person.fullName); // John Doe
person.fullName = "Alice Smith";
console.log(person.fullName); // Alice Smith
Getters and setters can encapsulate logic, ensuring internal properties remain consistent.
Object.defineProperty()
JavaScript provides Object.defineProperty()
to define getters and setters with more control over property behavior.
const person = { firstName: "John", lastName: "Doe" };
Object.defineProperty(person, "fullName", {
get() {
return `${this.firstName} ${this.lastName}`;
},
set(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
},
enumerable: true,
configurable: true
});
console.log(person.fullName); // John Doe
person.fullName = "Alice Smith";
console.log(person.firstName); // Alice
console.log(person.lastName); // Smith
enumerable: true
ensures the property shows up in loops or Object.keys()
.
configurable: true
allows redefining or deleting the property later.
Object.defineProperty()
is ideal for precise control, such as creating read-only or computed properties.
Setters are ideal for validating input before updating a property.
const student = {
_age: 18, // underscore indicates internal/private-like property
get age() {
return this._age;
},
set age(value) {
if (value < 0) {
console.log("Age cannot be negative");
} else {
this._age = value;
}
}
};
student.age = 20;
console.log(student.age); // 20
student.age = -5; // Age cannot be negative
The internal _age
property prevents infinite recursion inside the setter.
This technique is widely used for data integrity and encapsulation.
Getters allow dynamic computation without storing additional values.
const rectangle = {
width: 10,
height: 5,
get area() {
return this.width * this.height;
}
};
console.log(rectangle.area); // 50
area
is computed on demand.
Avoid heavy computations in getters to prevent performance issues.
Use getters for derived values: For example, full names, totals, or computed fields.
Use setters for validation: Ensure data integrity before updating values.
Avoid heavy computation in getters: Keep them lightweight.
Use underscores for private-like properties: Helps prevent recursion in setters.
Consider Object.defineProperty()
for advanced control over enumerability, configurability, or writability.
Provide controlled access to object properties.
Ensure data validation before assignment.
Enable computed or derived properties without storing extra data.
Encapsulate business logic within objects, improving readability and maintainability.
Essential for building robust applications with predictable behavior.
Getters are used to read properties dynamically.
Setters are used to modify properties with control and validation.
They can be defined directly in object literals or via Object.defineProperty()
.
Proper use of getters and setters ensures data integrity, encapsulation, and maintainable code.
They are a key concept for modern JavaScript development and object-oriented programming.
Mastering getters and setters is critical for any JavaScript developer, as they form the foundation for encapsulation, computed properties, and safe property updates in both simple scripts and complex applications.
Basic Getter
Create an object person
with firstName
and lastName
. Define a getter fullName
that returns the full name. Access and log fullName
.
Basic Setter
Add a setter fullName
to the same object that splits a string and updates firstName
and lastName
. Test it by assigning a new name.
Getter and Setter Together
Create an object student
with firstName
, lastName
, and a fullName
getter/setter. Access the full name, then update it via the setter, and log all properties.
Validation with Setter
Create a student
object with a private-like property _age
. Add a setter age
that prevents negative values. Test it with valid and invalid numbers.
Computed Property
Create a rectangle
object with width
and height
. Define a getter area
that computes the area dynamically. Log the computed area.
Object.defineProperty() Getter/Setter
Use Object.defineProperty()
to define a property fullName
with getter and setter for a person
object. Test reading and updating the property.
Dynamic Update via Setter
Create an object employee
with a setter for salary
that ensures the salary cannot be below 1000. Test updating the salary.
Private-like Property Access
Create an object account
with _balance
. Add a getter and setter to safely access and update _balance
. Log the updates.
Chained Setter Update
Create a setter for temperature
in a weather
object that converts Celsius to Fahrenheit internally and updates another property. Test the behavior.
Full Name Transformation
Create an object user
with firstName
and lastName
. Use a setter to update fullName
but automatically capitalize the first letters of both names. Log the result.
Do you want me to do that next?
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts